Here is my code for this simple assignment:
Write the code that will read character input from the user until a blank (a space) is entered. Print how many characters were entered. Keep in mind the user may decide to enter a blank as his first character.
Why is the space not ending the loop?
#include <iostream>
using namespace std;
int main(){
char answer;
int count=1;
do{
cout << "please enter number " << count;
cin >> answer;
count++;
}while(answer!=' ');
cout << "you entered " << count-1 << "numbers." << endl;
return 0;
}
The
cin >>operations skip all kinds of whitespace by default. You can usecin >> noskipws;before your loop to disable whitespace skipping or usecin.get()instead:You should be aware that newlines and carriage returns are no longer skipped now, so you have to handle them separately. Also, you should check the stream status to react to end-of-file: