简体   繁体   中英

Problems visualizing IOStream Buffer C++

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!

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM