Click here to Skip to main content
15,895,192 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The following code is from the recent edition of C++ Primer by Lippman

#include <iostream>
using std::cin;
using std::cout;
using std::endl;


int main()
{
    char ch;
    // initialize counters for each vowel
    int aCnt = 0, eCnt = 0, iCnt = 0, 
        oCnt = 0, uCnt = 0;

    while (cin>>ch ) {
    	// if ch is a vowel, increment the appropriate counter
    	switch (ch) {
    		case 'a':
    			++aCnt;
    			break;
    		case 'e':
            
    			++eCnt;
    			break;
    		case 'i':
            
    			++iCnt;
    			break;
    		case 'o':
            
    			++oCnt;
    			break;
    		case 'u':
                 
    			++uCnt;
    			break;
    	}
    }
    // print results
    cout << "Number of vowel a: \t" << aCnt << '\n'
         << "Number of vowel e: \t" << eCnt << '\n'
         << "Number of vowel i: \t" << iCnt << '\n'
         << "Number of vowel o: \t" << oCnt << '\n'
         << "Number of vowel u: \t" << uCnt << endl;
        system("pause");
    return 0;</iostream>


It shows its results extremly poorly. I can't make it read files. Other times
upon running, I type in characters and hit ^z then it shows after a long pause.
How can I make it work properly.
Posted
Comments
Albert Holguin 9-Jun-11 19:51pm    
how are you trying to make it read files?

1 solution

The while loop has no exit condition.

"How can I make it work properly?" — well, it depends what do you mean "properly". If you want, add a condition for exit right after line with while, such as
C++
while (cin>>ch ) {
   if (ch == 'q') break;
   switch (ch) {
      //...
   }
}

in this case the loop will exit on 'q' ("quit").

—SA
 
Share this answer
 
v4
Comments
TRK3 9-Jun-11 19:54pm    
Actually, while (cin>>ch) is the canonical way to scan an input until an error (including EOF) is encountered -- so it should work.

But personnally, I've never been fond of the C++ streams. For reading characters, I would always go with the tried and true C funtion: getchar() and test for EOF.
Albert Holguin 9-Jun-11 21:03pm    
cin is the standard input, which if default from the prompt, not from file... if OP doesn't have code to redefine cin, its going to be the default.
TRK3 10-Jun-11 12:26pm    
Depends on how he is invoking it. Could be invoking it from the command line with:

myprogram.exe < file.txt
Albert Holguin 13-Jun-11 13:34pm    
true
psych00range 14-Jun-11 0:02am    
i doubt hes invoking using commandline just on the knowledge that he has....it is always easier to have an exit condition for loops as debugging tool especially if your a beginner programmer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900