1

この形式のファイルを開く必要があります

Dat Nguyen 77.7 88.8 99.9 11.1 22.2

Pat Nguyen 2 3 4 5 6 

行の最初の名前を構造体のメンバー配列に割り当て、行の姓を構造体の別のメンバーに割り当て、行の各番号を構造体のスコアの配列に割り当てる必要があり、新しい各行は次の行に進みます構造体配列のインデックスで、同じことを行います (言い方が悪かったら申し訳ありません)。

名と姓の割り当てはうまくいきますが、番号を構造体メンバーに割り当てると、最初の 3 つの番号がスキップされます。私は何を間違っていますか?

これが私のコードです

void fileLoad(Gradebook *students, int &stuCount, int &assignments)
{
ifstream fin;
fin.open("Scores.txt");
if (!fin.is_open())
    cout << "Failed to open file.\n";

if (stuCount < 10)
{
    int n = 0;
    string tempLine;
    string line[10];
    while (!fin.eof())
    {
        getline(fin, tempLine);
        line[n] = tempLine;
        stringstream ss(tempLine);
        ss >> students[stuCount].fname >> students[stuCount].lname;
        assignments = 0;
        for (int i = 0; tempLine[i] != '\0'; i++)
        {
            ss >> students[stuCount].score[assignments];
            if (tempLine[i] == ' ')
                assignments++;

        }
        cout << line[n] << endl;
        assignments--;
        stuCount++;
        n++;
        cout << assignments << endl;
    }
}
else
    cout << "Already max students.\n";
}

ここに出力があります

Dat Nguyen 77.7 88.8 99.9 11.1 22.2


Pat Nguyen 2 3 4 5 6


1. Add a new student to the class
2. Assign grades for a new assignment
3. List one student, displaying all their grades and their course average
4. List all the scores for a chosen assignment
5. Display all grades currently contained in the gradebook
6. Save the gradebook to file
7. Exit the program
Enter choice: 3

Enter a student #: 1

Dat Nguyen

Assignment 1: 11.1

Assignment 2: 22.2

Assignment 3: -9.25596e+61

Assignment 4: -9.25596e+61

Assignment 5: -9.25596e+61

Assignment 6: -9.25596e+61

Average: -5.28912e+61
4

1 に答える 1

0

このビットのロジックは疑わしいです:

for (int i = 0; tempLine[i] != '\0'; i++)
{
    ss >> students[stuCount].score[assignments];
    if (tempLine[i] == ' ')
        assignments++;

}

tempLineこれは、すべての文字を1 つずつ反復し、から単語全体を読み取ろうとしますss。少し考えてみてください。すべての文字について、単語全体を読みます。ssのコピーが含まれていますがtempLine、それ以外は別個のエンティティです。ss単語サイズのブロックとサイズのブロックで読み取るとtempLinecharループが終了するずっと前に単語が使い果たされます。また、OP は単語の読み取りが成功するかどうかをテストしていないため、Crom は何が起こっているかしか知りません。

次のようなものが欲しいと思います:

while (assignments < MAX_ASSIGMENTS &&
       ss >> students[stuCount].score[assignments])
{ // read all assignments until array full or couldn't read an assignment score 
    assignments++;
}

MAX_ASSIGMENTSscore配列のサイズ設定に使用される OP のプレースホルダーです。

于 2016-03-11T22:41:28.953 に答える