Home > Back-end >  C - std::getline() returns nothing
C - std::getline() returns nothing

Time:04-10

I have a C function that reads a .txt file, however, when I run it, std::getline returns nothing. Therefore, the while loop on line 22 does not run.

How do I fix this function to return a vector where each line is a different item in the vector?

The file I am reading from a .txt file that has two lines:

testing
123

Here is my code:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

std::vector<std::string> readf(std::string filename)
{
    std::ifstream file(filename);
    file.open(filename);

    // Check if file is open
    if (!file.is_open())
    {
        std::cout << "Error opening file: " << filename << std::endl;
        exit(EXIT_FAILURE);
    }

    std::vector<std::string> lines;
    std::string line;

    // Read the file
    while (std::getline(file, line))
    {
        if (line.size() > 0)
            lines.push_back(line);
    }

    return lines;
}

CodePudding user response:

You don't need to invoke file.open(filename); because you already opened the file using the constructor std::ifstream file(filename);.

Invoking file.open(filename); after opening the file using the constructor causes the stream to enter an error state, because the file has not been closed yet.

See The difference between using fstream constructor and open function.

  •  Tags:  
  • c
  • Related