I/O流字符串操作(正确的Cin/cout运算符<</>)) [英] I/O Stream String Manipulation (Correct Cin/cout operators <</>>)
问题描述
我遇到了这个问题在这里,还对答案给出了另一个问题(由于我是stackoverflow的新手,所以我无法发表评论).回答这个问题的人似乎对替换<< >>用于cin
和cout
.但是我遇到的问题是所有分号都不会显示在新的输出文件中.
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.
我知道 while std::getline(input, command, ';')
会擦除所有分号,但是应该在末尾将它们与else语句放回去,但是在我运行它时不会被替换.如果我省略';'在getline
语句之外,输出文件中的所有内容都混乱了.
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.
如何显示分号呢?
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
}
}
}
推荐答案
问题在这里:
if (! first)
{
output << command; // write string to output
}
else
{
first = false;
output << ';' << command; // write string to output
}
在第一次迭代中,执行else
分支并打印分号.
In the first iteration, the else
branch gets executed and a semicolon is printed.
在以后的任何迭代中,将执行if
分支,这不会不打印分号.
In any later iteration, the if
branch is executed, which does not print a semicolon.
修复很容易:交换以output <<
开头的两行.
The fix is easy: Swap the two lines starting with output <<
.
这篇关于I/O流字符串操作(正确的Cin/cout运算符<</>))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!