I seem to be getting an infinite loop when I try to print all 128 ASCII values and I don't understand why. The question asks me to write a program that uses a loop to display the characters for the ASCII codes 0 through 127 and to display 16 characters on each line. I tried using a for loop and told the program to stop looping if my char variable goes past 127 but for some reason I end up getting an infinite loop. I even wrote an if-statement telling the loop to break if the char variable goes beyond 127 but that doesn't seem to work either. Here is my code, any feedback would be greatly appreciated, thank you.
#include <iostream>
using namespace std;
int main() {
char a;
for (char a = 0; a <= 127; a++)
{
cout << a << " ";
if (a % 16 == 0)
cout << endl;
if (a > 127)
break;
}
return 0;
}
Your char
type is almost certainly a signed one (C/C++ allow char
to be signed or unsigned (a)) so, when you add one to 127
, it's wrapping around to -128
(not actually mandated by the standard, but common behaviour).
Hence it's always less than or equal to 127
.
You can test that with the following code:
#include <iostream>
using namespace std;
int main() {
char x = 127;
x++;
cout << (int)x << endl;
return 0;
}
If that is the case, just use unsigned char
rather than char
.
Here's some code that does the job, while also only printing out the characters specifically marked as printable:
#include <iostream>
using namespace std;
int main() {
unsigned char a = 0;
while (a < 128) {
if (isprint(a)) {
cout << a << " ";
} else {
cout << ". ";
}
if (++a % 16 == 0) {
cout << endl;
}
}
return 0;
}
The results are:
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~ .
(a) From C++ 17, basic.fundamental
:
a plain
char
object can take on either the same values as asigned char
or anunsigned char
; which one is implementation-defined.