Published by
Dec 1, 2008 (last update: Feb 10, 2009)

Using cin to get user input.

Score: 3.8/5 (56 votes)
*****
Too many questions keep popping up with the same problem. How do I get user input from cin using >> into X type. Using the >> operator opens you up to alot of problems. Just try entering some invalid data and see how it handles it.

Cin is notorious at causing input issues because it doesn't remove the newline character from the stream or do type-checking. So anyone using cin >> var; and following it up with another cin >> stringtype; or getline(); will receive empty inputs. It's best practice to NOT MIX the different types of input methods from cin.

I know it's going to be easier to use cin >> integer; than the code below. However, the code below is type-safe and if you enter something that isn't an integer it will handle it. The above code will simply go into an infinite loop and cause undefined behaviour in your application.

Another dis-advantage of using cin >> stringvar; is that cin will do no checks for length, and it will break on a space. So you enter something that is more than 1 word, only the first word is going to be loaded. Leaving the space, and following word still in the input stream.

A more elegant solution, and much easier to use is the getline(); function. The example below shows you how to load information, and convert it between types.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

 string input = "";

 // How to get a string/sentence with spaces
 cout << "Please enter a valid sentence (with spaces):\n>";
 getline(cin, input);
 cout << "You entered: " << input << endl << endl;

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;
 }
 cout << "You entered: " << myNumber << endl << endl;

 // How to get a single char.
 char myChar  = {0};

 while (true) {
   cout << "Please enter 1 char: ";
   getline(cin, input);

   if (input.length() == 1) {
     myChar = input[0];
     break;
   }

   cout << "Invalid character, please try again" << endl;
 }
 cout << "You entered: " << myChar << endl << endl;

 cout << "All done. And without using the >> operator" << endl;

 return 0;
}