- Read in numbers from the user
- Read in strings from the user
- Read in strings which contain whitespace from the user
- Handle mixed input of strings and numbers
- Pause a program until a character is entered
Setting up C++ to get input from keyboard
- Before main(), include the iostream library: #include <iostream>
- Note: #include is NOT a C++ statement. It is a preprocessor directive. That is why there is no semicolon at the end of that line. It copies in text (C++ code) from another file.
- After the include, but before main(): using namespace std;
- Note: The using statement specifies what you want to use from the library. In this case, everything from the namespace named "std".
- If you wanted to just include cin (for console input), you could use: using std::cin;
Reading in a number from the keyboard
- Create a variable to hold the number and then use cin to read it from the keyboard.
- Example:
int faveNum;
cin >> faveNum;
- It is usually nice to prompt the user so they know what to type in. Example:
double amount;
cout << "Enter the amount: ";
cin >> amount;
- You can also read in strings. Example:
string name;
cout << "Enter your name: ";
cin >> name;
- Note that strings with whitespace (space, tab) in them will not be read properly using this technique.
- Note: If you are trying to read a number and the user types in a name, then your program will crash. When repetition (looping) is covered we will be able to correct this problem. That is called input validation.
Reading strings with whitespace
- You still need the same #include and using statement you used for regular input with cin.
- Use the getline function. Example:
string name;
cout << "Enter your name: ";
getline(cin, name);
- Note: getline will only read in strings, not numbers
- This works great until you try to use both cin and getline in the same program. You can have a getline and then a cin - but not a cin and then a getline. The reason for this is that cin will read a number from the keyboard and leave the newline the user entered at the end of the number. Then the getline function reads the newline and thinks that is the end of its input.
- The solution is to get rid of the extra newline after a cin before the getline function is called. cin.ignore() can be used for that purpose. Example:
int faveNum;
string name;
cout << "Enter your favorite number: ";
cin >> faveNum;
cin.ignore();
cout << "Enter your name: ";
getline(cin, name);
- Note: Do NOT use cin.ignore() after a getline function call. The getline function does NOT leave a newline in the buffer.
- You can use cin.get() to pause a program.
- cin.get() is used to read a single character from the keyboard. Example:
cout << "Press Enter to continue...";
cin.get();
- Note that cin.get() will work fine after a getline function call, but if it comes after a regular cin statement, then you need to have a cin.ignore() before it for the same reasons you had to have cin.ignore() between a cin and a getline.