C 从具有不同数据类型的文件中循环

c++ while loop from file with different data types

本文关键字:文件 循环 数据类型      更新时间:2023-10-16

我有一个包含此信息的文件:

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;
}

如使用循环所述,要获得所需的东西。另外,由于getline和提取返回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. ** " << "nn";
        return 1;
    }
    while ( getline( inScores , name ) )
    {
        if ( inScores >> loopCount )
        {
            cout << name << " has " << loopCount << " matches with scores of" << "nn";
        }
        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 << "nn";
    inScores.close();
    return 0;
}