我有一个包含此信息的文件:
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;
}
答案 0 :(得分:0)
如上所述,使用循环将是必要的,以获得你想要的。此外,由于getline和extract如果失败则返回false,您可以在循环中使用它们进行测试:
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 << '\n';
inScores.open( filename );
if ( !inScores )
{
cout << "** " << filename << " does not exist. Please ";
cout << "check the spelling and rerun ";
cout << "the program with an existing golfer file. ** " << "\n\n";
return 1;
}
while ( getline( inScores , name ) )
{
if ( inScores >> loopCount )
{
cout << name << " has " << loopCount << " matches with scores of" << "\n\n";
}
else
{
cout << "File read error";
return 1;
}
for ( int count = 1; count <= loopCount; count++ )
{
if ( inScores >> matchScore )
{
cout << "Match " << count << ": " << matchScore << '\n';
adder = adder + matchScore;
}
else
{
cout << "File read error";
return 1;
}
}
}
cout << '\n';
int( mean ) = .5 + ( adder / loopCount );
cout << "The mean score is " << mean << "\n\n";
inScores.close();
return 0;
}