Logic error

Hi, I'm having a problem with my code, no error, it's just the logic that is wrong


program asks for a char and then proceeds to ask for a phrase, it will count the char that the user chose and it will also count all the chars. Problem is when it's time to enter the phrase it doesn't give the time to the user to enter the phrase and it proceeds normally as if a phrase had been entered
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
using namespace std;
void main(){
	unsigned int ch;
	unsigned int NumOfChar = 0;
	unsigned int Total = 0;
	char CountingChar;
	cout << "Select a char to count: " << endl;
	cin >> CountingChar;
	cout << "Chosen char: " << CountingChar << endl;
	cout << "Insirt a phrase: " << endl;
	while ((ch = cin.get()) != '\n') {
		if (ch == CountingChar)
			++NumOfChar;
		++Total;
	}
	cout << "Number of " << CountingChar << "s : " << NumOfChar << endl;
	cout << "Total :" << Total << endl;
}


output

Select a char to count:
a
Chosen char: a
Insirt a phrase:
Number of as : 0
Total :0
Last edited on
After line 9 with cin>>countingChar the '\n' (enter character) is still left in the buffer.

It is this '\n' that is inputted in cin.get() ;

To fix this, ignore the next char input after the first input. .i.e
1
2
3
4
5
6
7
8
9
10
11
12

cin>>countingChar;
cin.ignore(); //will ignore the '\n';
cin.get(); //will now ask you for input.

OR

cin>>countingChar;
fflush(stdin); //flush (empty) input buffer
cin.get();


Thank you, it works fine now.
Topic archived. No new replies allowed.