#include <iostream> #include <string> int main() { std::cout << "Please enter your age: "; unsigned age = 0; std::cin >> age; std::cout << std::endl; std::cout << "Pease enter your name: "; std::string name; std::getline(std::cin, name); return 0; }
In this code we first input an unsigned type to represent a persons age. Then we input a persons name using std::string, and std::getline. We immediately notice a problem. It would seem that the std::getline statement is being skipped over. However, this is not the case. Lets take a closer look at how this program actually works.
First we are asked to enter an age. So lets assume that we enter the age of 25. However, after entering 25 we also press enter. So our input actually looks like this 25'\n'. Note the newline character at the end, which is added when we press the enter key. The std::cin >> age; statement removes 25 from the input stream, and places it in the variable age. The '\n' character however, is still in our input stream. After we are asked to enter a name, the std::getline(std::cin, name); statement is executed. std::getline uses the '\n' character as its delimiter, by default. If you remember there was a '\n' character left over from our previous input statement. So getline looks at the input stream and the first character is sees is the '\n' character, which is getlines delimiter. So getline removes the '\n' character from the stream, and discards it. Getline then stops processing the stream. From a users perspective it would appear that the getline statement was skipped over altogether.
Ok but how do we fix this problem? there are many ways to solve this problem, but the simplest solution looks like this.
Ok but how do we fix this problem? there are many ways to solve this problem, but the simplest solution looks like this.
#include <iostream> #include <string> int main() { std::cout << "Please enter your age: "; unsigned age = 0; std::cin >> age; std::cout << std::endl; std::cout << "Pease enter your name: "; std::string name; std::cin.ignore(); std::getline(std::cin, name); return 0; }
In this code we call std::cin.ignore(); before std::getline. This removes the '\n' character from the input stream. Since the input stream is now completely empty, std::getline will wait for the user to enter some data.
Great! but what if the code looks more like this?
#include <iostream> #include <string> int main() { std::cout << "Please enter your age: "; unsigned age = 0; std::cin >> age; std::cout << std::endl; std::cout << "Pease enter your name: "; std::string name; std::cin >> name; return 0; }
Do we still have to put a std::cin.ignore(); statement before std::cin >> name;?
The answer is no. Remember the '\n' character is considered to be whitespace, and the extraction operator (>>) automatically ignores leading whitespace. So the '\n' character is ignored automatically.
No comments:
Post a Comment