سؤال

I have a problem with a loop, what i want to do is copy a file, line by line. I used this code but it in the output file write one more bracket and one line.

void copyStringNewFile(ifstream& inData,ofstream& outData)
{
string x = "";

while (inData)
{
    getline(inData, x);
    outData << x << '\n';
}
}

Probably i can remove the line:

string x = "";

In the while conditions I've tried a few solution:

while (!inData.eof())    // Works similar to while (inData)

while (inData >> x)      // Delete a lot of lines

Thank you so much, and if you can explain where eof can be useful (because in loops it seems useless).

هل كانت مفيدة؟

المحلول

You are not checking the return value of getline(). When it fails, no copy should be made. Btw, you are also depending on a final '\n' in the source file, otherwise you'll have trouble copying the last line.

Here's a form that monitors successful reads properly:

void copyStringNewFile(ifstream& inData, ofstream& outData)
{
    char ch;
    while (inData >> ch)
    {
        outData << ch;
    }
}

Or if you're ready to use a more advanced form:

void copyStringNewFile(ifstream& inData, ofstream& outData)
{
    outData << inData.rdbuf();
}

نصائح أخرى

You probably want:

while (getline(inData, x)) {
    outData << x << '\n';
}

You are seeing the last line duplicated because you are testing the stream and THEN trying to read from it; the status of the stream as "EOF" is only set after trying - and failing - to read.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top