简体   繁体   中英

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. Why?

Turn on your warning options !! ( -Wextra for GCC)

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.

When x reach 127 it's flipped to -128 in the next round [-128 to 127]

DEBUG SCREEN

American Standard Code for Information Interchange. ASCII Character Set. A char variable in C++ is a one-byte memory location where a single character value can be stored. Because one byte can hold values between 0 and 255 that means there are up to 256 different characters in the ASCII character set.

Now For your solution, you can try below code up to 127 or complete 256

Very Simple : For printing ASCII values of all characters in C++, use a for loop to execute a block of code 255 times. That is, the loop variable I start with 0 and ends with 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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