23rd Jan 2018, 9:26 AM
Sumit Verma
Sumit Verma - avatar
2 Answers
+ 8
http://www.cplusplus.com/reference/istream/istream/ignore/ istream& ignore (streamsize n = 1, int delim = EOF); Extract and discard n characters in the input stream until delim is reached. E.g. If your input stream consists of: "qwerty.youip" std::cin.ignore(3, '\n') would result in "rty.youip" remaining in the input stream. (Extracted and discarded 3 characters in the input stream) std::cin.ignore(200, '.') would result in "youip". (Extracted and discarded characters until delimiting character '.' is reached). More reference: https://www.sololearn.com/discuss/616181/?ref=app ***************************************** Now, let's look at your code: double num; string mystr; cout << "Please enter a number: " << "\n"; cin >> num; cout << "Your number is: " << num << "\n"; cin.ignore(256, '\n'); cout << "Please enter your name: \n"; getline (cin, mystr); We can see that you have a cin statement prior to your getline statement. What happens when you input 12345 For example, is registered in the stream as "12345\n" when you submit it for input by hitting the Enter key. The newline character at the end of the input stream will be extracted and placed into mystr by getline, if you do not use cin.ignore to discard it.
23rd Jan 2018, 9:35 AM
Hatsy Rei
Hatsy Rei - avatar
+ 7
Generally, cin.ignore() is used to discard the content of input stream in order to have a "garbage free" input stream buffer for the next input, from what I read once, it is suggested to use cin.ignore() if we mix the use of getline() with the >> operator for getting inputs, and it is also advised to use when we get false from cin.good(), where it means the stream is "clogged" by "garbage" data. Please correct me if I'm wrong : ) Hth, cmiiw
23rd Jan 2018, 9:40 AM
Ipang