用c ++从文件中读取数据

时间:2015-07-06 22:15:35

标签: c++ file-io

我尝试做书练习。我完全做到了。但是,我坚持一点,我可以使用inputStream >> name来保持数据,但使用相同的逻辑,我无法使用inputStream >> score。还应该有效吗?有没有错误的思考?

score.txt的内容

Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000

以下代码效果很好:

#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();
}

那个不是:

#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();
}

1 个答案:

答案 0 :(得分:1)

您说您的文件如下:

c = [a[i] for i in b]

然而你的代码却是:

Ronaldo
10400
Didier
9800
...

您正在尝试首先读入int,并破坏文件处理程序。切换这两个,你的代码应该工作:

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