while loop with '\0' as a signal

I have to print an ASCII value of each character in a char array, 1 per line. I have to use a while loop and look for the '\0' as a signal to end. This is the code if have so far but it does not work. I am not sure how to write the while statement for this. If anyone can help me I would appreciate it.

Thanks,
Randy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

  char sName[30] = "bob jones";
  cout << "Enter a new name" << endl;
	cin.getline(sName,30);
	cout << endl;
	cout <<"sName is now " << sName << endl;

	cout << endl;


	while(sName != '\0')
	{
		cout << (int)sName << endl;
		sName++;
	}
sName is an array and not a pointer so you can not increment the address of it(arrays have constant address). You can however do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
int i = 0;
while( sName[i] ) //not equal to '\0' == 0
{
    cout << (int)sName[i] << endl;
    ++i; //you could put i++ in the subscript of sName
}

//or this:

for( int i = 0; sName[i]; ++i )
{
    cout << (int)sName[i] << endl;
}
Thanks giblit!

I think I got it now. This will print out the ASCII value of each character. Here is the new code:

int i = 0;
while(sName[i] != '\0')
{
cout << (int)sName[i] << endl;
i++;
}

Thanks again!
Topic archived. No new replies allowed.