简体   繁体   English

可视化IOStream Buffer C ++的问题

[英]Problems visualizing IOStream Buffer C++

I know that iostream would have buffers to store I/O data. 我知道iostream会有缓冲区来存储I / O数据。 Say, I have some C++ code like this. 说,我有一些这样的C ++代码。 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. C ++代码由于StackOverflow不允许我将图像嵌入该问题,因此,如果您不想单击链接,请使用以下代码。

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? cin.ignore(1)为什么起作用? 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. 缓冲区不会像\\ n \\ n那样有两个\\ n,因为我先按两次cin >> Val1,然后再按cin >> Val2来按Return / Enter键。 And according to this StackOverflow question cin>> should leave the \\n in the stack. 并根据此StackOverflow问题 cin >>应将\\ n留在堆栈中。 Thus, I thought only cin.ignore(2), which discards two first chars in the buffer, works. 因此,我认为只有cin.ignore(2)可以在缓冲区中丢弃两个第一个字符。 Also, 也,

getline(cin >> ws, String_Val);

works as well according to this StackOverflow thread . 根据此StackOverflow线程也可以正常工作 Shouldn't ws remove whitespaces only, and shouldn't whitespaces be represented differently from newline \\n in the buffer? 我们不应该只删除空格吗?在缓冲区中,空格是否应与换行符\\ n表示不同?
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 . 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. 默认情况下, cin >>在读取值之前将跳过任何前导空格,因此将在读取Val2之前跳过Val1之后的任何换行符。 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. 这就是为什么在读取Val2之后仅忽略一个字符可能会起作用的原因,但是如果用户放置了任何多余的空格,它将无法按预期工作(您将忽略一个空格字符,但是getline()然后将读取其他所有内容Val2在同一行上。

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: 您会发现很多SO问题,这些问题显示并解释了如何以一种健壮的方式忽略直到下一个换行符的所有内容,但总而言之:

#include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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