Loop issue/question

Aug 28, 2014 at 7:59pm
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;
}
Aug 28, 2014 at 8:22pm
= is used for assignment.
== is used for comparison.
Aug 28, 2014 at 8:31pm
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.

Look at this post - http://www.cplusplus.com/forum/general/2541/ for converting from integer to character type.
Aug 28, 2014 at 9:05pm
@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;
    }



Last edited on Aug 28, 2014 at 9:08pm
Aug 28, 2014 at 9:16pm
Thanks for the help, I have it working now!
Aug 28, 2014 at 9:50pm
Thanks @AbstractionAnon, I didn't know about that.
Aug 28, 2014 at 10:19pm
Instead of a b variable you could just do (int)a or static_cast<int>(a)
Topic archived. No new replies allowed.