Search code examples
c++file-ioinputifstreamistream

C++: ifstream::getline problem


I am reading a file like this:

char string[256];

std::ifstream file( "file.txt" ); // open the level file.

if ( ! file ) // check if the file loaded fine.
{
    // error
}

while ( file.getline( string, 256, ' ' )  )
{
    // handle input
}

Just for testing purposes, my file is just one line, with a space at the end:

12345 

My code first reads the 12345 successfully. But then instead of the loop ending, it reads another string, which seems to be a return/newline.

I have saved my file both in gedit and in nano. And I have also outputted it with the Linux cat command, and there is no return on the end. So the file should be fine.

Why is my code reading a return/newline?

Thanks.


Solution

  • First leets make sure your input file is good:

    Run the following command and let us know the output:

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <iterator>
    #include <fstream>>
    #include <iomanip>
    #include <algorithm>
    
    int main()
    {
        std::ifstream file("file.txt");
        std::cout << std::hex;
    
        std::copy(std::istreambuf_iterator<char>(file),
                  std::istreambuf_iterator<char>(),
    
                  std::ostream_iterator<int>(std::cout, " ")); 
    }
    

    Edit:

    The output was 31 32 33 34 35 20 0A

    Try running this code and see what the output is:

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <iterator>
    #include <fstream>>
    #include <iomanip>
    #include <algorithm>
    
    int main()
    {
        std::ofstream file("file.txt");
        file << "12345 \n";
    }
    

    Dump the output of this file and compare it to the original.
    The problem is that different platforms have different line termination sequences. I just want to verify that '0x0A' is the line termination sequence for your platform. Note the line termination sequence is converted into a '\n' when a file is read in text mode and when you output '\n' to a file in text mode it is converted to the line termination sequence.

    Edit 2

    So I have the file: file.txt

    > od -ta -tx1 file.txt
    0000000    1   2   3   4   5  sp  nl                                    
               31  32  33  34  35  20  0a                                    
    0000007
    

    So the file contains 1 line terminated with 0x0A

    Using this program:

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <iterator>
    #include <fstream>>
    #include <iomanip>
    #include <algorithm>
    
    int main()
    {
        std::ifstream   file("file.txt");
    
        std::string line;
        while(std::getline(file,line))
        {
            std::cout << "Line(" << line << ")\n";
        }
    }
    

    I get:

    > g++ t.cpp
    > ./a.out
    Line(12345 )