從文本文件中讀取,直到EOF重復最后一行以下內容C+代碼使用如果流對象從文本文件(每一行有一個數字)中讀取整數,直到它命中。EOF..為什么它要讀取最后一行的整數兩次?怎么解決這個問題?代碼:#include <iostream>#include <fstream>using namespace std;int main(){
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;}輸入txt:10 20 30輸出量:10 20 30 30注:我跳過了所有錯誤檢查代碼,以保持代碼片段的小。在Windows(Visual C+)、cygwin(GCC)和Linux(GCC)上都可以看到上述行為。
3 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
抓10 抓20 抓取30 抓斗EOF
while (true) { int x; iFile >> x; if( iFile.eof() ) break; cerr << x << endl;}

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
ifstream iFile("input.txt"); // input.txt has integers, one per lineint x;while (iFile >> x) { cerr << x << endl;}

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
#include <iterator>#include <algorithm>// ... copy(istream_iterator<int>(iFile), istream_iterator<int>(), ostream_iterator<int>(cerr, "\n"));
- 3 回答
- 0 關注
- 705 瀏覽
添加回答
舉報
0/150
提交
取消