[英]Displaying the contents of a specified text file in c++
我試圖使該程序要求用戶輸入文本文件的名稱,並使其顯示文本文件中的結果。 當我運行該程序時,它在某種程度上成功了,因為它可以識別文本文件,但是會輸出奇怪的結果。 例如,我正在嘗試使其輸出包含以下內容的某個文件的內容:
10 5 70
5 15 85
12 9 75
10 6 60
20 10 100
15 8 95
4 3 35
20 10 200
9 5 65
但是它只輸出:
0 0 0
到達文件末尾
我對C ++真的很陌生,但是我一直在努力弄清楚為什么我的程序無法正常工作,而且無論如何,這只是最終程序的一小部分。 謝謝!
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int count, firstMinute, secondMinute, numOfDishes;
string inputFileName;
ifstream inputFile;
cout << "Input file name: ";
getline(cin, inputFileName);
//Open input file
inputFile.open(inputFileName);
//check if messed up
if (!inputFile.is_open())
{
cout << "Unable to open file." << endl;
exit(1);
}
while (inputFile >> firstMinute >> secondMinute >> numOfDishes)
{
cout << firstMinute << ' ' << secondMinute << ' ' << numOfDishes <<
' ' << '\n';
}
cout << "End of file reached" << endl;
inputFile.clear();
inputFile.seekg(0);
inputFile.close();
return 0;
}
首先, while(!inputFile.eof())
不是一個好主意。 在這里更多。
此外,您根本不會更改firstMinute
, secondMinute
和numOfDishes
。 您是否忘記在循環中這樣做?
我本來只是使用提取運算符而不是像這樣的getline()
:
while(inputFile >> firstMinute >> secondMinute >> numOfDishes) //not checking for eof
{
cout << firstMinute << ' ' << secondMinute << ' ' << numOfDishes << '\n';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.