假设有一场比赛,我们有x场比赛,还有y名选手。每一场比赛,每一位参赛者都能得到0到10分之间的分数。所以有一个文件,看起来像这样(当然没有点):
我的问题是,这里字符串和整数是交替的,我不知道如何将它们放入多维数组中。
下面是我如何做到这一点,如果只有整数在一个文件。是否可以修改它,这样我就可以在我的程序中使用它?
string x;
int score,row=0,column=0;
int marray[10][10] = {{0}};
string filename;
ifstream fileIN;
cout<<"Type in the name of the file!"<<endl;
cin>> filename;
fileIN.open(filename);
while(fileIN.good()) //reading the data file
{
while(getline(fileIN, x))
{
istringstream stream(x);
column=0;
while(stream >> score)
{
marray[row][column] = score;
column++;
}
row++;
}
}发布于 2014-04-07 22:20:45
数组(甚至多维数组)是同构的,所有条目都必须是相同类型的。该属性允许CPU通过简单的置换操作计算数组中任何条目的地址。
在这种情况下,您希望存储一个字符串和一个整数。因此,您可以简单地使用结构作为数组的条目。
struct Result {
Result() : point(0)
{}
std::string contestantName;
unsigned int point;
};
Result results[10][10];代码的其余部分与您编写的代码非常相似。
https://stackoverflow.com/questions/22924041
复制相似问题