0

My function reads a file and puts it into a string in order for me to process it. I need to read just before EOF, obviously. The problem is that the EOF character is also put inside the string and I can't find a way to bypass it, since it leds other parts of the program to fail. I link the function below.

    string name_to_open, ret = string();
    ifstream in;

    getline(cin, name_to_open);
    in.open(name_to_open.c_str());
    if (!in.is_open()) {
        cout << "Error." << endl;
        return string();
    }
    else {
        ret += in.get();
        while (in.good()) {
            ret += in.get();
        };
    };
    in.close();
    return ret;

The function reads fine until the end of the file, then appends EOF and \0. How can I solve the problem? Does the EOF character work fine in controls? I also tried to put a line ret[ret.size() - 1] = '\0'; at the end of the cycle, but this doesn't seem to work either.

A O
  • 65
  • 5

1 Answers1

3

ret += in.get(); appends the character read from the tile to the string whether the value read was good or not. You need to 1) read, 2) test that the read is valid and the value read is safe to use, 3) use the value read. Currently your code reads, uses, and then tests whether or not the value read was safe to use.

Possible solution:

int temp;
while ((temp = in.get()) != EOF) // read and test. Enter if not EOF
{
    ret += static_cast<char>(temp); // add the character
};

Note: get returns an int, not a char. This is to be able to insert out-of-band codes such as EOF without colliding with an existing valid character. Immediately treating the return value as a char could result in bugs because a special code may be mishandled.

Note: there are many better ways to read an entire file into a string: How do I read an entire file into a std::string in C++?

user4581301
  • 29,019
  • 5
  • 26
  • 45