0

I know that iostream would have buffers to store I/O data. Say, I have some C++ code like this. C++ code Since StackOverflow doesn't allow me to embed an image to this question yet, here's the code in case you don't want to click on the link.

int main(){

int Val1, Val2;
string String_Val;
cin >> Val1;
cin >> Val2;
cin.ignore(1);
getline(cin, String_Val);   
}

Why does the cin.ignore(1) work? Here's My idea of how the buffer looks like.
Wouldn't the buffer have two \n like \n\n because I hit the Return/Enter key twice by cin>> Val1 and then by cin>>Val2. And according to this StackOverflow question cin>> should leave the \n in the stack. Thus, I thought only cin.ignore(2), which discards two first chars in the buffer, works. Also,

getline(cin >> ws, String_Val);

works as well according to this StackOverflow thread. Shouldn't ws remove whitespaces only, and shouldn't whitespaces be represented differently from newline \n in the buffer?
Lastly, it would really help if someone happens to know any interactive program or ways to help me visualize the buffer as the program runs. Something like https://visualgo.net. Thanks a ton!

  • "Since StackOverflow doesn't allow me to embed an image to this question yet, here's the code in case you don't want to click on the link." you should just post code as text even when you gain the privilege to embed images https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question – Matteo Italia Feb 04 '18 at 02:27
  • "whitespace" is not only spaces, but also some other blank characters, like tab and newline. – Bo Persson Feb 04 '18 at 03:22

1 Answers1

0

You code doesn't work reliably. By default, cin >> will skip any leading whitespace before reading the value, so any newline after Val1 will be skipped before Val2 is read. That's why ignoring just one character after reading Val2 may work, but if the user's put in any extra whitespace it won't work as intended (you'll ignore one whitespace character but the getline() will then read anything else up to the end of the same line Val2 was on.

You'll find lots of SO questions showing and explaining how to ignore everything through to and including the next newline in a robust way, but summarily:

#include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • So cin wouldn't actually discard the chars in the buffer, but simply moving the current pointer to the right? Something like http://users.monash.edu/~cema/courses/CSE2305/Topics/12.23.CaseStudy/html/streambuf.gif ? And are you implying that whitespaces and \n are represented in the same way in the buffer? So when I hit Enter/Return key on the console, would the buffer store \n or whitespace? – Viet Long Le Nguyen Feb 04 '18 at 03:00