Hi, I was hoping someone could help me with a C++ string problem. I currently have my program open up a file, read the contents into a string, and then I am trying to look for certain key characters in the string, like < and </. In short, I am trying to read an XML type file.
Here is my code so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string document;
string temp;
ifstream infile;
infile.open("file.txt");
while (! infile.eof())
{
infile >> temp; // Put contents of infile (file.txt) into temp. Temp is here b/c it will be used later at some point....
document += temp; // Put contents of temp into document.
}
cout << document << endl; // read document to varify string is correct
for(int i=0; i<document.length(); i++) {
if (document[i] = '<') { cout << endl << "'<' encountered" << endl; //Go to a function that takes care of the rest of the file. I will pass the string and 'i' to it.
};
}
infile.close();
system("pause");
return 0;
}
I currently have a text document (file.txt) that looks like this:
<name first>joe</name>
<name first>ann</name>
<name>bob builder</name>
and the program spits out this:
<namefirst>joe</name><namefirst>ann</name><name>bobbuilder</name>
'<' encountered
'<' encountered
'<' encountered
some more of them in here.... as many of them as there are characters in the file.
'<' encountered
'<' encountered
'<' encountered
Press any key to continue . . .
The program also strips out white spaces. I guess there not really necessary, but if anyone knows how to preserve them that would be nice.
By the way, when I make if (document[i] = '<')
into if (document[i] = "<")
, i get a invalid conversion from `const char*' to `char'
error.