a problem about switch&while statement.

This is an example about switch statement in the book I'm reading.
This program is used to determine how many vowels in a char.
Here are the codes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char ch;
int vowelCnt = 0;

cin >> ch;

switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
	++vowelCnt;
	break;
}


if i input "good", vowelCnt will be 0;

but if i change "cin >> ch;" into "while(cin >> ch)"
i mean
1
2
3
4
5
6
7
8
9
10
11
12
13
while(cin >> ch)
{
	switch(ch)
	{
	case 'a':
	case 'e':
	case 'i':
	case 'o':
	case 'u':
		++vowelCnt;
		break;
	}
}


I input "good" again,then input "ctrl + z" to exit input,
but now, vowelCnt is 2, which is quite different from the former program.

I'm really confused.
why result change from 0 to 2?
Thanks in advance.
Last edited on
Because without the while loop you only read one character (g) which isn't a vowel. So the count remains 0. With the while loop, you read the whole word, and find two vowels (the o's), so the count is incremented to 2.

Because without the while loop you only read one character (g) which isn't a vowel. So the count remains 0. With the while loop, you read the whole word, and find two vowels (the o's), so the count is incremented to 2.


Thank you very much.
Would you please explain more detailedly? Y with the while loop, it will read the whole word. and without the loop, it will only read the first character?
Um, I'll see what I can do...

Without the loop: there is one read, and the program continues normally. Since there is no loop, none of that code is every repeated.

With the loop: there is a read at the start of the loop; you input 'g', which is good data, so it enters the loop. It's not a vowel, so it doesn't increment the counter. It reaches the end of the loop, and checks the condition again. This entails reading another character. It reads a 'o', which is good data, so it enters the loop. It's a vowel, so the counter is incremented. It reaches the end of the loop, and checks the condition again. This entails reading another character. It reads a 'o', which is good data, so it enters the loop. It's a vowel, so the counter is incremented. It reaches the end of the loop, and checks the condition again. This entails reading another character. It reads a 'd', which is good data, so it enters the loop. It's not a vowel, so the counter isn't incremented. You then input Ctrl+z, which is EOF if I recall correctly, so the loop terminates.

...Wordy, but I hope that helps.
You mean the condition for while statement is whether the character of word is good data, not whether a word is correctly input( EOF is not inputed)?

I hope i don't misunderstand you.
When you input an EOF character, then the while loop evaluates cin as being false.
Topic archived. No new replies allowed.