缓冲区如何工作? [英] How buffers are working ?
本文介绍了缓冲区如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我打开一个包含两行的文件(sample.txt),现在如果我在while循环中声明字符串,我在屏幕上得到两行但是如果我在循环中声明字符串,我在控制台上获得第二行两次。任何人都可以解释发生了什么。缓冲区在其中扮演什么角色?
I am opening a file(sample.txt) containing two lines, now if I declare string in while loop, i get two lines on screen but if I declare string outside while loop i am getting second line twice on console. Can any one explain whats happening . Is buffers playing any role in it?
int main()
{
ifstream itf("Sample.txt");
if(!itf)
{
cout << "Not able to open file :("<<endl;
exit(1);
}
string str;
while(itf)
{
getline(itf, str);
cout <<str;
}
return 0;
}
推荐答案
我认为缓冲区运行正常。
Buffers are working fine, I suppose.
引用:
但如果我声明字符串外部while循环我在控制台上获得第二行两次
but if I declare string outside while loop i am getting second line twice on console
这不应该发生,事实上它不会发生在我运行您发布的代码的系统上。
This shouldn't happen, and in fact it doesn't happen on my system running the code you posted.
更改cout
运算符以在最后添加换行符,因此:
Change yourcout
operator to put a newline at the end, thus:
cout <<str << endl;
这应该是你的输出清除。
which should make your output clearer.
您应该在getline
之后和<之前检查itf
code> COUT 。当它读取第二行时,应该没有错误,因此在循环顶部检查的条件(itf)
仍应返回true
。循环然后第三次运行,但由于没有其他内容可读,getline
什么都不做,显然也没有重置str
。以下cout然后再次打印未更改的str
,虽然有错误!
作为一般规则,在使用结果之前,请务必检查读取操作是否成功!
You should checkitf
aftergetline
and before thecout
. When it reads the second line, there should be no error, and therefore the condition(itf)
checked at the top of your loop should still returntrue
. The loop then runs a third time, but since there is nothing else to read,getline
does nothing and it apparently also does not resetstr
. The following cout then simply prints the unchangedstr
again, although there was an error!
As a general rule, always check the success of read operations before using the result!
这篇关于缓冲区如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文