我只是有点困惑:成员函数 putback() 将读取的最后一个字符放回到输入流中。这到底是什么意思?我尝试对其进行试验,发现无论是否使用 putback(),文件的结果都没有差异。
*我有两个文本文件:内容为“5 2”的input.txt和运行前没有内容的output.txt。
例如
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char next;
ifstream fin;
ofstream fout;
fin.open("input.txt");
fout.open("output.txt");
if((fin.fail())||(fout.fail()))
{
cout<<"File failed to open files";
return 1;
}
while(next!='2')
{
fin.get(next);
fout.put(next);
}
fin.putback(next);
cout<<"This is next:"<<next;
return 0;
}
最佳答案
putback
将其参数放回输入流,使其成为下一个要读取的字符。要在工作中查看它,请将循环更改为以下内容并观察程序进入无限循环:
while (next != '2') {
fin.get(next);
fin.putback(next); // This will cause an infinite loop
fout.put(next);
}
发生这种情况是因为您读取的第一个 5
将立即放回输入流,导致 next
永远不会变成 2
。
关于C++ putback() 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446084/