我有一个看起来像这样的文件:
Mike 1200
John 350
Jen 1500
Tara 700
Michelle 2000
Kevin 500
Matt 450
Kim 200
我存储内容的代码:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
const int MAX = 15;
int main() {
// declare variables
string names[MAX];
string tempscore;
float scores[MAX];
fstream infile;
infile.open("winners.txt", ios::in);
int cc = 0;
getline(infile, names[cc], ' ');
infile.ignore( 0, ' ');
infile >> tempscore;
infile.ignore( 1, '\n');
scores[cc] = strtof(tempscore.c_str(), NULL);
cout << "'" << names[cc] << "'" << endl;
cout << "'" << scores[cc] << "'" << endl;
int i = 1;
while (infile) {
getline(infile, names[i], ' ');
infile.ignore( 0, ' ');
infile >> tempscore;
infile.ignore( 1, '\n');
scores[cc] = strtof(tempscore.c_str(), NULL);
cout << "'" << names[i] << "'" << endl;
cout << "'" << scores[i] << "'" << endl;
i++;
}
infile.close();
return 0;
}
大多数名称都正确存储,但没有一个分数。为什么?我究竟做错了什么?
这是完成我想要实现的目标的最佳方式吗?