这似乎是一个老问题,但这里的问题不是使用了两个 cin.get(),而是使用了两个以上!如果我写(在 DEV C++ 中)
我只收到一个输入请求,然后结束程序。现在,我预计至少有两个 cin 请求,因为我预计:
char s[50];
char t[100];
char r[100];
char f[100];
cin.get(s,49);
cin.get(t,99);
cin.get(r,99);
cin.get(f,99);
我至少处理了 2 个输入请求,因为:
first cin: buffer empty,I insert the string s and \n
second cin: I have in buffer \n still, then t=\n without input request
third cin: buffer empty, I insert the string r and \n
fourth cin: I have in buffer \n still, then f=\n without input request
但我只有 s 字符串的输入请求! 为什么我只有一个输入请求?缓冲区没有用第二个 cin.get 清除,让第三个 cin.get 正常工作?谢谢
最佳答案
t
不等于 '\n'
。它是空的。 .get(char*,int)
将从不从缓冲区中删除'\n'
。
更糟糕的是,尝试读取 t
会将 cin
设置为失败状态,因为无法读取任何内容,这将导致所有后续读取 任何类型 从 cin
立即失败,甚至不尝试直到你 .clear()
失败状态。
这是令人惊讶的行为,但根据问题的最后一句话,您似乎已经猜到了大部分,所以,干得好!你在学习!
关于C++ 多个 cin.get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716353/