Search code examples
c++ifstream

Ifstream.get reads only first line


I have the following program

ifstream input;
input.open("File.txt",ios::in);
while(input){
    char arr[30];
    input.get(arr,30);
    cout << arr;
}

My file is

A 100
B 200

However, my output has only the first line, that is A 100. When I replace .get with .getline it works as expected.

I did some searching and found that .get keeps the \n in the stream, while .getline removes it altogether.

Is that the reason why I'm getting only the first line? If it is, how do I fix it?


Solution

  • The answer is yes. You found already the problem. After "A 100" has been read, the '\n' will still be in the stream. The next get will again not read the '\n' and return an empty string. And again and again. So this will never work.

    You coud use std::ignore or ifstream::getline.

    However, I would recomend none. Reason: You should not, never and never ever use C-Style arays like char arr[30]; in C++. Never.

    Simply use a std:::string.

    See:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    
    int main()
    {
        std::ifstream input{ "r:\\File.txt" };
        std::string line{};
        while (std::getline(input,line)) {
            std::cout << line << '\n';
        }
        return 0;
    }