fstream and replace question

Hello, I'm supposed to be able to replace a word within an input file (and in this case my input file is my main.cpp file) with the same word but in uppercase form. Here is my code:


int main()
{
string line;
ifstream inputfile ("input.txt"); // declares input stream
ofstream outputfile ("output.txt"); // declares output stream


if (inputfile.is_open())

{
while ( getline (inputfile, line) )

{
if (line.find("else ") != string::npos)
{
line.replace(line.find("else "),4 , "ELSE ");


// Finding else and replacing it with ELSE
}

else if (line.find("if ") != string::npos)
{
line.replace(line.find("if "), 2, "IF");


// Finding if and replacing it with IF
}

else if (line.find("while ") != string::npos)
{
line.replace(line.find("while "), 5, "WHILE");


// Finding while and replacing it with WHILE
}

outputfile << line << "\n"; // Copy code from inputfile to outputfile but with substitutions
}




inputfile.close(); // closing inputfile

}


else cout << "Error. Unable to open file"; // if opening inputfile fails, prompt error message


}



Every time I run this and check the output file, it returns something like this:

IF (inputfile.is_open())

{
WHILE ( getline (inputfile, line))

{
if (line.find("ELSE ") != string::npos)
{
line.replace(line.find("ELSE "), 5, "ELSE ");


// Finding ELSE and replacing it with ELSE
}

ELSE if (line.find("if ") != string::npos)
{
line.replace(line.find("IF "), 3, "IF ");


// Finding IF and replacing it with IF
}



It doesn't replace every single "if" with "IF" and I'm not sure why

thanks.
¿do you know what else means?

look at how the lines were replaced
if (line.find("ELSE ") != string::npos)
ELSE if (line.find("if ") != string::npos)
Last edited on
Topic archived. No new replies allowed.