读取多种类型文件我有一个看起来像这样的文件:C++在同一条线上
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;
}
大部分的名称都存储正确但没有一个分数是。为什么?我究竟做错了什么?
这是做我想达到的最好方法吗?
好吧,所以我读了所有的答复, m不熟悉stringstream方法,重新格式化我的文件不是我的选择。因此,我使用了我最熟悉的方法。 我编辑我的代码,它似乎工作,除了现在我在我的名字[]'数组中获得一个额外的(空白)名称和文件(200)最后的分数也被追加两次。一次用于“Kim”,另一个用于空白名称。 任何想法,为什么这是这样吗? –
@EliNahon:你不检查getline(infile,names [i],'');'是否成功。最后一次失败,但你继续。读到tempscore失败,但你继续已经在tempscore。我将举例说明如何使用stringstream方法做到这一点。 – stefaanv
@EliNahon:请参阅编辑。斯特凡诺夫已经指出了问题的原因 –