简体   繁体   中英

Failbit set when trying to read from file - why?

I'm trying to write a function that automatically formats XML-Strings; but I'm already failing when I try to read text from a file and write it into another one.

When I use my function sortXMLString()

bool FormatXML::sortXMLString()
{
    string XMLString;
    ifstream fin("input.txt");
    fin.open("input.txt", ios::in);
    ofstream fout("output.txt");
    fout.open("output.txt", ios::out);
    if (fin.is_open() && fout.is_open())
    {
        if (fin.good()) cout << "good" << endl;
        if (fin.fail()) cout << "fail" << endl;
        if (fin.bad()) cout << "bad" << endl;
        while (getline(fin, XMLString))
        {
            //TODO: Formatting
            fout << &XMLString << endl;
        }
        fin.close();
        fout.close();
    }
    else return false; 
    return true;
}

I will get the output "fail", but the function never enters the while-loop. The function returns true. It doesn't matter what I write into my input.txt (a single letter, a single number, multiple lines of text or even nothing), the failbit will always be set before getline can even be reached. Why is this/ how can I properly read out of my file?

ifstream fin("input.txt"); will open the file with fin as stream object why calling open member function again ? same goes for fout object too.

Calling open on an already open stream fails, meaning the failbit flag is set to true.

Just open once

ifstream fin("input.txt");
ofstream fout("output.txt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM