从文件读取到结构数组

时间:2013-11-28 20:22:25

标签: c++ arrays struct io

首先,我想说这是我的CS161课程的作业,所以虽然直接的答案会很好,但一个很好的解释对我来说更有帮助。我们本周已经介绍了结构,但是我的代码有些问题。我现在的目标是从一个名为“QBInfo.txt”的文件中读取三个结构的数组。

struct QuarterBack{
    string name;
    int completions[kNumGames];
    int attempts[kNumGames];
    int yards[kNumGames];
    int touchdowns[kNumGames];
    int interceptions[kNumGames];
};

QuarterBack players[kNumPlayers] = {player1, player2, player3};

另外,如果有帮助我应该说kNumPlayers是一个设置为3的常量,而kNumGames是一个设置为10的常量。

这是我用来从我的文件中读取的代码。虽然它似乎没有用,但我一直不知道为什么,所以我想我可能会向社区寻求帮助。

ifstream myIF;
    myIF.open("QBInfo.txt");
    string trash;
    string temp;
    getline(myIF, trash);
    for(int i = 0; i < kNumPlayers; i++){
        getline(myIF, temp);
        players[i].name = temp;
        for(int j = 0; i < kNumGames; j++){
            myIF >> players[i].completions[j];
            myIF >> players[i].attempts[j];
            myIF >> players[i].yards[j];
            myIF >> players[i].touchdowns[j];
            myIF >> players[i].interceptions[j];
        }
    }

以下是我的讲师提供的测试用例文件。第一个数字用于分配的挑战部分,由于时间限制,我将在稍后尝试。这是我的循环开始之前getline(myIF, trash)部分代码的原因。

3
Peyton Manning              
27  42  462 7   0
30  43  307 2   0
32  37  374 3   0
28  34  327 4   0
33  42  414 4   1
28  42  295 2   1
29  49  386 3   1
30  44  354 4   3
25  36  330 4   0
24  40  323 1   0
Tom Brady               
29  52  288 2   1
19  39  185 1   0
25  36  225 2   1
20  31  316 2   0
18  38  197 0   1
25  43  269 1   1
22  46  228 0   1
13  22  116 1   1
23  33  432 4   0
29  40  296 1   1
Drew Brees              
26  35  357 2   1
26  46  322 1   2
29  46  342 3   1
30  39  413 4   0
29  35  288 2   0
17  36  236 2   1
26  34  332 5   0
30  51  382 2   2
34  41  392 4   0
30  43  305 1   1

2 个答案:

答案 0 :(得分:1)

使用istringstream使用从文件中读取的数据填充结构成员。 在诸如此类的短程序中命名可能不是特别重要 - 但考虑传达意义的变量名称是一个好习惯。 数据文件似乎具有第一行中的玩家数量。 getline用来读过这一行。通常情况下,这将用于初始化玩家数量变量。

std::ifstream infile;
infile.open("qb.dat");
std::string nPlayers;
std::string playerName;

getline(infile, nPlayers);
getline(infile, playerName);

for (int player = 0; player < kNumPlayers; ++player)
{
  for (int game = 0; game < kNumGames; ++game)
  {
    std::string dataRow;
    getline(infile, dataRow);
    std::istringstream is(dataRow);
    is >> players[player].completions[game] >>
          players[player].attempts[game] >>
          players[player].yards[game] >>
          players[player].touchdowns[game] >>
          players[player].interceptions[game];
  }
}

答案 1 :(得分:1)

您的计划到底有什么不正确的结果?

对于第二个for循环中的一件事,有一个错误i < kNumGames而不是j < kNumGames

然后你应该至少检查一下文件是否成功打开了:

if( !myIF )
{
    // open failed
    return 1;
}

然后行getline(myIF, temp);出现问题。它只会在第一次工作,因为第二次到达该行时,您的阅读位置将在您读取的最后一个数字之后和换行符之前。这是第二个getline调用将返回一个空字符串,然后你将尝试从玩家名称中读取数字。

您可以通过在内部for循环之后添加getline(myIF, trash);来快速解决此问题。

相关问题