我需要创建一个struct
的数组,而struct
是学生(数据类型string
firstName,string
LastName,int
TestScore和char
等级(。我已经弄清楚了功能原型的逻辑,并且我学到了一些基本文件I/O。我希望有20名结构中的学生,并且将从.txt文件中读取信息。这是我遇到麻烦的地方。这是我的基本代码。
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
struct studentType {
string firstName;
string lastName;
int testScore;
char Grade;
};
int main()
{
studentType students[20];
int i;
ifstream inputFile;
inputFile.open("testScores.txt");
for (i = 0; i < 20; i++)
inputFile >> students->testScore;
cout << "The test scores entered are: ";
for (i = 0; i < 20; i++)
cout << " " << students->testScore;
return 0;
}
当您访问数组时,您会忘记从数组中索引元素。更改:
students->testScore
to:
students[i].testScore
在两个循环中。第一个版本仅更改第一个元素(因为可以使用*students
访问(,而第二个则将索引添加到指针中。
这只是使用std::vector
或std::array
的另一个很好的理由,因为如果您尝试像在此处的数组一样放弃它们,您将获得一个明显的错误。
在旁注中,在C 中,您应在内部声明循环变量您的循环。在C99之前必须在外面宣布它们,但不是C 。