我有一个问题。如果我不在文件末尾放置空格,为什么我的程序不读取最后一个整数?如果我有一个只有编号的文本文件,没有结束空间,程序就不会读取任何内容。
这是我的计划:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream f1,f2;
int k;
int q;
cout << "Inserisci numero lettere da leggere : ";
cin >> q;
f1.open("in.txt", ios::in);
f2.open("out.txt", ios::out);
if(f1.fail()){
cout << "Impossibile aprire il file";
exit(1);
}
f1 >> k;
while( !f1.eof() && q > 0){
q--;
cout << k << '\n';
f2 << k;
f1 >> k;
}
f1.close();
f2.close();
return 0;
}
答案 0 :(得分:2)
您的程序读取了所有数字,但在读取操作后进行了!f1.eof()
检查。当最后一个数字后面有一个文件结尾时,你永远不会输出它。
替换
f1 >> k;
while( !f1.eof() && q > 0){
q--;
cout << k << '\n';
f2 << k;
f1 >> k;
}
与
while( f1 >> k && q > 0){
q--;
cout << k << '\n';
f2 << k;
}
阅读一些关于input/output via streams的文章。