2

I want to read a file with std::getline. but reads first line only

string FileReader::readLine() {

    string line;
    string read;
    ifstream ReadFile;
    ReadFile.open("input.txt");

    if (ReadFile.is_open()) {
        getline(ReadFile, line);

      //ReadFile.close();
    }
    return line;
}

this is my method. I call this method several time but always reads first line how can i do to read next lines?

  • 1
    Maybe using a *loop*? – Some programmer dude Dec 05 '18 at 05:38
  • Are you wanting to save the whole file into one string? Or are you wanting to store each line in a container like an array or vector? Right now `getline()` is reading the first line and then you're done. – cwbusacker Dec 05 '18 at 05:41
  • no i dont want whole file into string. i want to save line by line. i call method several time but cant read other lines – Hakan Bakacak Dec 05 '18 at 05:43
  • 3
    You open a file anew with each call, so you always start reading from the beginning. You need to open the file once, then call `getline` multiple times, then close it when you are done reading. – Igor Tandetnik Dec 05 '18 at 05:44
  • What you want is a co-routine. Behold C++ 20. – Sahil Dhoked Dec 05 '18 at 05:54
  • I dont know co-routine – Hakan Bakacak Dec 05 '18 at 05:55
  • [Coroutine](https://stackoverflow.com/questions/553704/what-is-a-coroutine). It's a bit excessive for this. All you need to do is store `ReadFile` so you don't have to keep opening it on every call. Open the file in the caller and pass `ReadFile` into the function or similar. Or do as Yvette Colomb suggests in her answer and just read the whole file in one pass. Hard to give good suggestions because we don't really know what you need to do with the lines you're reading. – user4581301 Dec 05 '18 at 06:13
  • i decide to save whole file into vektor – Hakan Bakacak Dec 05 '18 at 09:23

1 Answers1

1

You need to change your program flow.

Don't return a string. Use the line within the loop to do whatever it is you want. Ensuring that you either don't leave the method or return to it.

You can't keep coming back to a function like this, as it will keep reading from the beginning.

void FileReader::readLine() {

    string line;
    string read;
    ifstream ReadFile;
    ReadFile.open("input.txt");

    if (ReadFile.is_open()) {
        while(getline(ReadFile, line))
        {
            //do what you want with that line, but return program flow here.
        }
        ReadFile.close();
    }
}