1
我有一個包含此信息的文件:C++,同時從不同數據類型的文件循環
Bev Powers
3
76 81 73
Chris Buroughs
5
88 90 79 81 84
Brent Mylus
2
79 81
我有一個計數控制的循環,將做正確的前3行和使用信息,但我在努力使用循環將重複使用該循環,直到文件中顯示所有信息,而不管文件上有多少個匹配的高爾夫球手。我在向正確的方向徵求指點,任何援助將不勝感激。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream inScores;
string filename;
string name;
int loopCount, matchScore;
int count = 1;
float mean = 0;
float adder = 0;
int main()
{
cout << endl << "Enter the golfer's filename: ";
getline(cin,filename);
cout << endl;
inScores.open(filename.c_str());
if(!inScores)
{
cout << "** " << filename << " does not exist. Please ";
cout << "check the spelling and rerun ";
cout << "the program with an existing golfer file. ** " << endl << endl;
return 1;
}
getline(inScores,name);
inScores >> loopCount;
cout << name << " has " << loopCount << " matches with scores of" << endl << endl;
inScores >> matchScore;
while (count <= loopCount)
{
cout << "Match " << count << ": " << matchScore << endl;
adder = adder + matchScore;
adder = adder + matchScore;
inScores >> matchScore;
count++;
}
cout << endl;
int(mean) = .5 + (adder/loopCount);
cout << "The mean score is " << mean << endl << endl;
inScores.close();
return 0;
}
您的第一步是擺脫'>>'。將'std :: getline'與'>>'混合[產生意外的結果](http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction)。使用'std :: getline'閱讀三行文本。爲第二行和第三行構建一個「std :: istringstream」,然後使用'std :: istringstream'解析它們。 –
請閱讀前兩行,爲接下來的N個值使用for循環,並將所有內容包裝在while循環中。可能最好將N值的讀數放在一個函數中,它會更漂亮。 –