Reputation: 33
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?
Upvotes: 3
Views: 816
Reputation: 47854
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");
Upvotes: 6