问题:为什么我在输入完第一组数据后,输入EOF(Ctrl+D)终止第一组数据输入,第二组数据尚未等我输入即已结束?
相关代码
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec1;
vector<int> vec2;
int tmp;
cout << "Input the Vec1`s elements:";
while (cin >> tmp) {
vec1.push_back(tmp);
}
cout << endl << "Input the Vec2`s elements:";
while (cin >> tmp) {
vec2.push_back(tmp);
}
return 0;
}
相关贴图(测试环境:Xcode 7.3.1 OSX EI Capitan)
个人思考
思考:个人认为,本问题应该属于缓冲区问题,可能是EOF(Ctrl+D)留在了缓冲中,然后直接被读入第二组数据,从而第二组数据未读取即结束。但我尝试在读取第二组数据前增添诸如 fflush(stdin)等清空输入缓冲等方法后,依旧无效。求各位高人指教,谢谢!
1. It is indeed an input problem, but it is also a problem with the flow status bits. When you enter a number, eof will be recognized as a character and stored in the buffer. The failbit is set instead of eof. After entering the number, enter the line feed and then eof, the eof bit is set. The following program can reflect this.
2. If you run the program according to the topic, even if eof is performed correctly, since eof is set after the end of the first while, the second while loop will still not be executed. When clear() is added, as long as the eof is correct, the subject's expectations can be achieved and the second while loop is entered for input. However, if you simply add the clear method and enter eof directly after the number, since eof is stored in the buffer as a character, after the second loop starts, the stream will still set the character when it detects the character in the buffer. The failbit causes the loop to exit.
3.fflush is useful. But it must be used in conjunction with cin.clear(), because status bits and buffering are two different concepts. Even if the buffer is cleared, the status bit should still be what it is. After using fflush, you can achieve direct eof without line breaks (cin.clear() followed by cin.ignore() can achieve the same function).
Environment: win10 64-bit + vs2015 community edition
See c++ reference/istream
for detailsIn addition, this is not a buffering problem, but istream has a flag indicating eof, so it is normal for fflush(stdin) to be useless.
After research, it is determined that the problem is an environmental problem, but there is currently no way to solve this problem. I don’t know if it is related to the compiler