私は大学入学システムをエミュレートするC++プログラムを作成しようとしています。学生はIDを入力し、テキストファイルで情報を検索し、テキストファイル。私は、登録されたコースを構造体の配列に取得するのに問題が発生している点に気づきました。 getline関数を使用して、 '、'をデリミアとして使用すると、次のカンマまで次の行を引き継ぎます。これに対して正しいアルゴリズムは何でしょうか?コンマで区切られたテキストファイルを配列に読み込む
これは偽学生情報が含まれているファイルのセットアップです:
- 918273645、スティーブ、オルブライト、ITCS2530、MATH210、ENG140
- 123456789、キム、マーフィー、ITCS2530、MATH101
- 213456789 、ディーン、バウアーズ、ITCS2530、ENG140
- 219834765、ジェリー、クラーク、MGMT201、MATH210
(レイアウト用の箇条書きが追加されました。
たとえば、ユーザーは自分のIDに「123456789」と入力し、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私が取り組んでいるコードのスニペットで質問を更新しました。 –