简体   繁体   中英

Data reading from file in c++

I try to do book exercise. I have done exactly. But, I'm stuck on at one point that I can hold datas eof by using inputStream >> name but using same logic, I can't hold by using inputStream >> score . Should also it have been worked ? Is there wrong thinking?

Content of score.txt

Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000

The following code works well:

#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>

using namespace std;

void getHighScore( string& holdName, int& holdScore );

int main() {

    string name;
    int score;

    getHighScore( name, score );


    cout << "High scored player is " << name
         << " score is " << score << endl;

    return 0;
}
void getHighScore( string& holdName, int& holdScore ) {

    ifstream inputStream;
    inputStream.open( "score.txt" );

    if ( !inputStream.is_open() ) {

        cout << "Error file opening\n";
        exit(0);
    }

    int highScore = -1;
    holdScore = highScore;

    int score;
    string name;
    while ( inputStream >> name ) {


        //inputStream >> name;
        //cout << name;
        inputStream >> score;
        if (score > holdScore) {

            holdScore = score;
            holdName = name;
        }
    }

    inputStream.close();
}

That one not:

#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>

using namespace std;

void getHighScore( string& holdName, int& holdScore );

int main() {

    string name;
    int score;

    getHighScore( name, score );


    cout << "High scored player is " << name
         << " score is " << score << endl;

    return 0;
}
void getHighScore( string& holdName, int& holdScore ) {

    ifstream inputStream;
    inputStream.open( "score.txt" );

    if ( !inputStream.is_open() ) {

        cout << "Error file opening\n";
        exit(0);
    }

    int highScore = -1;
    holdScore = highScore;

    int score;
    string name;
    while ( inputStream >> score ) {


        inputStream >> name;
        //cout << name;
        //inputStream >> score;
        if (score > holdScore) {

            holdScore = score;
            holdName = name;
        }
    }

    inputStream.close();
}

You say that your file looks like:

Ronaldo
10400
Didier
9800
...

And yet your code reads:

while ( inputStream >> score ) {
    inputStream >> name;

You are trying to read into an int first, and breaking your file handler. Switch those two and your code should work:

while ( inputStream >> name) {
    inputStream >> score;
    ...

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