简体   繁体   English

当我的 char 变量达到 [del] 字符 (127) 值时,为什么我的程序会进入无限循环?

[英]Why does my program enters into an infinite loop when my char variable reaches the [del] character (127) value?

Here's my code:这是我的代码:

#include <iostream>

int main()
{
    char x = 32;
    while (x <= 126) {
        std::cout << x << "\n";
        x += 1;
    }
}

Until here, all goes right, but if I change my code to:到这里为止,一切正常,但是如果我将代码更改为:

#include <iostream>

int main()
{
    char x = 32;
    while (x <= 127 /* here the "bad" change */ ) {
        std::cout << x << "\n";
        x += 1;
    }
}

to try to print the [del] character, my program goes into an infinite loop and starts to print a lot of other characters which I don't want.为了尝试打印 [del] 字符,我的程序进入无限循环并开始打印许多我不想要的其他字符。 Why?为什么?

Turn on your warning options !!打开您的警告选项 ( -Wextra for GCC) -Wextra的 Wextra)

test.cpp: In function 'int main()':
test.cpp:41:15: warning: comparison is always true due to limited range of data type [-Wtype-limits]
   41 |     while ( x <= 127 )
      |             ~~^~~~~~

I guess the warning message is pretty self-explanatory.我想警告信息是不言自明的。

Every value that fits into an 8-bit signed variable is less than or equal to 127. So if your platform uses 8-bit signed variables to hold characters, your loop will never exit.适合 8 位有符号变量的每个值都小于或等于 127。因此,如果您的平台使用 8 位有符号变量来保存字符,您的循环将永远不会退出。

When x reach 127 it's flipped to -128 in the next round [-128 to 127]当 x 达到 127 时,它会在下一轮翻转到 -128 [-128 到 127]

DEBUG SCREEN调试屏幕

American Standard Code for Information Interchange.美国标准信息交换码。 ASCII Character Set. ASCII 字符集。 A char variable in C++ is a one-byte memory location where a single character value can be stored. C++ 中的 char 变量是一个单字节 memory 位置,可以存储单个字符值。 Because one byte can hold values between 0 and 255 that means there are up to 256 different characters in the ASCII character set.因为一个字节可以保存 0 到 255 之间的值,这意味着 ASCII 字符集中最多有 256 个不同的字符。

Now For your solution, you can try below code up to 127 or complete 256现在对于您的解决方案,您可以尝试以下代码,最多 127 或完成 256

Very Simple : For printing ASCII values of all characters in C++, use a for loop to execute a block of code 255 times.非常简单:要打印 C++ 中所有字符的 ASCII 值,请使用 for 循环执行代码块 255 次。 That is, the loop variable I start with 0 and ends with 255.即循环变量 I 以 0 开始,以 255 结束。

#include<iostream>
using namespace std;
int main()
{
char ch;
int i;
cout<<"Character\t\tASCII Value\n";
for(i=0; i<255; i++)
{
    ch = i;
    cout<<ch<<" | "<<i<<endl;
}
cout<<endl;
return 0;
}

Thank you to all, I've replaced the char variable's type with an unsigned one and now the program works fine, here's my new code:谢谢大家,我已将 char 变量的类型替换为无符号类型,现在程序运行良好,这是我的新代码:

#include <iostream>
int main()
{
    unsigned char x = 0;
    while (x < 255) {
        x += 1;
        std::cout << short int(x) << ":\t" << x << "\n";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM