[英]Why does my program enters into an infinite loop when my char variable reaches the [del] character (127) value?
這是我的代碼:
#include <iostream>
int main()
{
char x = 32;
while (x <= 126) {
std::cout << x << "\n";
x += 1;
}
}
到這里為止,一切正常,但是如果我將代碼更改為:
#include <iostream>
int main()
{
char x = 32;
while (x <= 127 /* here the "bad" change */ ) {
std::cout << x << "\n";
x += 1;
}
}
為了嘗試打印 [del] 字符,我的程序進入無限循環並開始打印許多我不想要的其他字符。 為什么?
打開您的警告選項! ( -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 )
| ~~^~~~~~
我想警告信息是不言自明的。
適合 8 位有符號變量的每個值都小於或等於 127。因此,如果您的平台使用 8 位有符號變量來保存字符,您的循環將永遠不會退出。
當 x 達到 127 時,它會在下一輪翻轉到 -128 [-128 到 127]
美國標准信息交換碼。 ASCII 字符集。 C++ 中的 char 變量是一個單字節 memory 位置,可以存儲單個字符值。 因為一個字節可以保存 0 到 255 之間的值,這意味着 ASCII 字符集中最多有 256 個不同的字符。
現在對於您的解決方案,您可以嘗試以下代碼,最多 127 或完成 256
非常簡單:要打印 C++ 中所有字符的 ASCII 值,請使用 for 循環執行代碼塊 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;
}
謝謝大家,我已將 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.