简体   繁体   中英

reading characters and integers from text file

I am unable to read data from a text file. The data is in the following format:

Balto 85 83 77 91 76
Mickey 80 90 95 93 48
Minnie 78 81 11 90 73
Doc 92 83 30 69 87
Pluto 85 72 49 75 63
Grumpy 27 31 52 74 83

I have to calculate the sum of integers in front of every name. No strings allowed, no arrays! Can somebody help me with this??

code i've tried so far is:

int main()
{
    ifstream infile;
    char b;
    int x, i=0, sum=0, j=1;

    infile.open("input.txt");

    if (infile.fail())
    {
        cout<<"Unable To Open Input File, File Not Found!!"<<endl;
        exit(1);
    }

    while (i < 6)
    {

        infile.get(b);

        while (b != ' ')
        {
            cout<<b;
            infile.get(b);
        }

        infile>> x;

        while (j<=5)
        {
            sum = sum + x;
            infile>> x;

            j++;
        }

        cout<<"'s Average is: "<<sum/5<<endl;

        i++;

    }

The problem is here:

while (j<=5) {
   sum = sum + x;
   infile>> x;

   j++;
}

After the first line j is always 5. So, the loop that gets the numbers and calculates the average simply doesn't start. Just reset the j back to 1 after the loop:

while (j<=5) {
    sum += x;
    infile >> x;

    j++;
}

cout << "Average is: "<< sum / 5.0f << endl;

i++;
j = 1;
sum = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM