Detecting EOF in C++ from a file redirected to STDIN

前端 未结 3 1775
暗喜
暗喜 2020-12-17 06:20

Executing the command:

./program < input.txt

with the following code checking:

string input;
while(cin) {
  getline(cin,         


        
3条回答
  •  [愿得一人]
    2020-12-17 06:50

    @Jacob had the correct solution but deleted his answer for some reason. Here's what's going on in your loop:

    1. cin is checked for any of the failure bits (BADBIT, FAILBIT)
    2. cin reports no problem because nothing has yet been read from the file.
    3. getline is called which detects end of file, setting the EOF bit and FAILBIT.
    4. Loop executes again from 1, except this time it exits.

    You need to do something like this instead:

    std::string input;
    while(std::getline(std::cin, input))
    {
         //Have your way with the input.
    }
    

提交回复
热议问题