问题
I came across this question on here and had a further question about the answer give (I can't comment since I'm new to stackoverflow). The guy who answered it seems to be right about replacing << >> for cin
and cout
. But the problem I'm having is that all the semi-colons won't show up in the new output file.
I know that while std::getline(input, command, ';')
erases all semicolons, but theyre supposed to be put back with the else statement at the end, but it isn't being replaced when I run it. And if I omit ';' out of the getline
statement everything in the output file messes up.
How do you make it show that the semi-colon does show?
void print(ifstream& input,ofstream& output)
{
bool first = true;
std::string command;
while(std::getline(input, command, ';'))
{ // loop until no more input to read or input fails to be read
if (command.find("cin")!= std::string::npos)
{ // found cin somewhere in command. This is too crude to work. See below
size_t pos = command.find("<<"); // look for the first <<
while (pos != std::string::npos)
{ // keep replacing and looking until end of string
command.replace(pos, 2, ">>"); // replace with >>
pos = command.find("<<", pos); // look for another
}
}
else if (command.find("cout")!= std::string::npos)
{ // same as above, but other way around
size_t pos = command.find(">>");
while (pos != std::string::npos)
{
command.replace(pos, 2, "<<");
pos = command.find(">>", pos);
}
}
if (! first)
{
output << command; // write string to output
}
else
{
first = false;
output << ';' << command; // write string to output
}
}
}
回答1:
The problem is here:
if (! first)
{
output << command; // write string to output
}
else
{
first = false;
output << ';' << command; // write string to output
}
In the first iteration, the else
branch gets executed and a semicolon is printed.
In any later iteration, the if
branch is executed, which does not print a semicolon.
The fix is easy: Swap the two lines starting with output <<
.
来源:https://stackoverflow.com/questions/40414721/i-o-stream-string-manipulation-correct-cin-cout-operators