我的c ++程序的cout输出,打印到控制台但重叠。
例如:
while(pFile.good()){
getline (pFile, pLine);
cout<<pLine;
}
此代码打印最后一行,以及上一行的一些剩余部分。
我在cygwin上使用vi。这件事发生了。我改变了一些设置吗?
答案 0 :(得分:1)
getline()
会丢弃遇到的任何换行符。为了防止代码将所有行合并为一个大行,您需要这样做:
cout << pLine << endl;
正如克里斯指出的那样,你也应该使用getline()
作为while
条件。否则,现在可以将流视为“好”,但在呼叫getline()
时达到EOF。所以试试这个循环:
while (getline(pFile, pLine)) {
cout << pLine << endl;
}
答案 1 :(得分:0)
这里你是在同一行写作,因为getline只是丢弃了新行字符,这就是为什么你要写<<endl
while(pFile.good()){
getline (pFile, pLine);
cout<<pLine<<endl;
}
答案 2 :(得分:0)
最后一行打印两次的原因是因为您最后一次调用getline()失败了,但仍然打印pLine
(即使其内容未定义)。
while(pFile.good()){
getline (pFile, pLine); // What happens if this line fails.
// Like when you read **past** the end of file.
cout<<pLine;
}
您的代码的正确版本是:
while(pFile.good()){
if (getline (pFile, pLine))
{ cout<<pLine;
}
}
但这通常写成:
while(getline (pFile, pLine))
{
// The loop is only entered if the read worked.
cout<<pLine;
}
请记住,上次成功调用getline()会读取最多但不会超过行尾。这意味着下一次调用getline()将失败并设置EOF位。
另请注意,您的输出是拼凑在一起的,因为您没有在线之间添加'\ n'选择器。注意:getline()会读取下一个'\ n'字符,但此终止字符不会添加到字符串pLine
。