我想在C++中编写一个程序,模拟大学招生系统,学生输入他们的ID,程序搜索文本文件中的信息,并加载一个基于文本文件。我已经到了一个地步,我无法将他们的注册课程放入结构数组中。使用getline函数,使用','作为分隔符还会在下一行继续,直到下一个逗号。什么才是正确的算法呢?阅读逗号分隔文本文件到数组
这是文件的设置包含假学生信息:
- 918273645,史蒂夫,奥尔布赖特,ITCS2530,MATH210,ENG140
- 123456789,金,墨菲,ITCS2530,MATH101
- 213456789院长,鲍尔斯,ITCS2530,ENG140
- 219834765,杰里,克拉克,MGMT201,MATH210
(子弹添加布局;不在文件中)
例如,用户输入“123456789”作为他们的ID,然后读取Kim Murphy的信息。在getline的第一次迭代中,读取“ITCS2530”并将其放入变量中,然后加载到结构中;那里没有问题。但是,列表中的最后一个过程在下一个逗号前有换行符,因此下一次迭代将读取“MATH101/nl213456789”,并将整个字符串放入变量中,并尝试将其加载到结构中。
第一列是他们的ID,然后是他们的名字,姓氏,然后是他们当前注册的课程。请注意,注册课程的数量可能会有所不同。
这里是我目前工作的代码:
student login()
{
string ID;
student newStudent;
string enrolled;
int i = 0;
while (true)
{
cout << "Enter Student ID: ";
cin >> newStudent.ID;
cout << endl;
if (newStudent.ID.length() == 9)
break;
else
cout << "That ID is invalid - IDs are 9 digits" << endl;
}
ifstream inFile;
ofstream outFile;
inFile.open("registration.txt");
if (inFile.is_open())
//Check if file is open
{
while (!inFile.eof())
//While not at end of file
{
getline(inFile, ID, ',');
//Search for ID
if (ID == newStudent.ID)
{
getline(inFile, newStudent.fName, ',');
//Assign fName and lName
getline(inFile, newStudent.lName, ',');
while (enrolled != "\n")
{
getline(inFile, enrolled, ',');
if (enrolled == "\n")
{
cout << "Not currently enrolled in a class." << endl;
}
else
{
newStudent.courses[i] = enrolled;
i++;
}
}
cout << newStudent.lName << ", Welcome to the MCC Enrollment System!" << endl;
for (i = 0; i <= NUM_OF_COURSES; i++)
{
cout << "Enrolled courses: " << newStudent.courses[i] << endl;
}
cout << endl;
break;
//Stops searching
}
else
//Ignores rest of line - used to skip to the next line
{
getline(inFile, ID, '\n');
}
if (inFile.eof())
//If ID was not found
{
inFile.close();
cout << "Enter First Name: ";
//Begin entry of new student
cin >> newStudent.fName;
cout << endl;
cout << "Enter Last Name: ";
cin >> newStudent.lName;
cout << endl;
outFile.open("registration.txt", ios::app);
if (outFile.is_open())
{
outFile << newStudent.ID << "," << newStudent.fName << "," << newStudent.lName << "\n";
}
}
}
}
return newStudent;
}
预先感谢任何帮助。
你能显示你的代码吗? – Default
我们需要了解如何从文件中获取数据。我们需要看到的原因是fgets,fscanf,std :: cin和std :: getline都获取由换行符或空格分隔的数据。 –
@JerryJeremiah我用我正在编写的代码片段更新了这个问题。 –