Hello, I've been trying to learn using one of Stroustrup's books, and I'm running into an issue on one of the exercises. It asks to use a loop to write out a table of characters with their corresponding integer values like this:
a 97
b 98
...
z 122
etc etc. I'm able to get 'a 97' to loop indefinitely but I can't seem to get the variable to increment properly. All I get is
a 97
a 97
a 97
repeatedly down the screen. Any insight into what I'm doing wrong here would be greatly appreciated! Below is the code.
Thanks!
Ben
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
char a;
a = 'a';
int b;
b = a;
while (a= 'a'){
cout << a << '\t' << b << '\n';
++a;
}
return 0;
}
Hi Ben,
The problem in your code is you are trying to increment char value in line 9. That's not going to work. You can start with int b =97 and increment that. Try to print char value of that by using typecasting to char. You can refer to the post below for casting from one type to another. Hope this helps.
@funprogrammer - You most certainly can increment a char.
There are a couple of problems here.
1) The improper use of assignment verses comparison at line 7 as Peter87 pointed out. The variable a gets reassigned to the value 'a' each time line 7 is executed.
2) If the = operator in line 7 is replaced with ==, the loop will only execute once. When the variable a is incremented at line 9, a will no longer equal 'a' and the loop will terminate.
3) You also want to increment b inside your loop.
7 8 9 10 11
while (a <= 'z')
{ cout << a << '\t' << b << '\n';
++a;
++b;
}