The >> operators are for inputting formatted text. You must either use low-level input functions (like cin.get()) or input text with ENTER in mind:
1 2 3 4 5 6 7 8 9 10 11 12 13
// low-level.cpp
#include <iostream>
usingnamespace std;
int main()
{
cout << "Press the ENTER key";
if (cin.get() == '\n')
cout << "Good job.\n";
else
cout << "I meant ONLY the ENTER key... Oh well.\n";
return 0;
}
// intelligent-input.cpp
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
vector <pair <int, int> > pairs;
string s;
int a, b;
cout << "Enter a list of pairs of integers, one pair per line, as\n 1 2\n""Press ENTER on a blank line to finish.\n\n> ";
// While there is input and the user has not simply pressed ENTER
while (getline( cin, s ) && !s.empty())
{
stringstream ss( s );
ss >> a >> b;
if (!ss)
cout << "Invalid pair. Try again";
else
pairs.push_back( make_pair( a, b ) );
cout << "> ";
}
// Now get a single number from the user, which we'll use to search the list
cout << "\nThank you. Now enter a number to find> ";
while (getline( cin, s ))
{
if (stringstream( s ) >> a) break;
cout << "Invalid integer. Try again> ";
}
// Count the number of times the user's number appears in the list
b = 0;
for (vector <pair <int, int> > ::iterator p = pairs.begin(); p != pairs.end(); p++)
{
if (p->first == a) b++;
if (p->second == a) b++;
}
switch (b)
{
case 0: cout << "That number does not appear in the list.\n";
case 1: cout << "That number appears in the list 1 time.\n";
default: cout << "That number appears in the list " << b << " times.\n";
}
cout << "\nThanks for playing. Bye!\n";
return 0;
}
Both examples work because user input is line buffered, meaning that the user must press ENTER before your program will see any input at all. That is also how users expect the program to behave.
Hope this helps.
[edit] BTW, the examples are larger than they needed to be. I've provided complete programs you can play with. For the second example, the points of interest are on lines 19..28.