【问题标题】:C++ sstream skipping first three inputs from a fileC ++ sstream跳过文件中的前三个输入
【发布时间】:2016-03-11 21:12:50
【问题描述】:

我需要打开这种格式的文件

Dat Nguyen 77.7 88.8 99.9 11.1 22.2

Pat Nguyen 2 3 4 5 6 

我需要将行的名字分配给结构的成员数组,将行的姓分配给结构的另一个成员,将行的每个编号分配给结构中的分数数组,并且每个新行都去到结构数组的下一个索引,做同样的事情(对不起,如果我措辞不好)。

我的名字和姓氏分配很好,但是当它开始将数字分配给结构成员时,它会跳过前三个数字。我做错了什么?

这是我的代码

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

【问题讨论】:

  • 永远不要使用while (!fin.eof())
  • @Nathan 用什么代替?
  • while (!fin.eof()) 替换为while (getline(fin, tempLine)) 并从循环体中删除getline()
  • 我试过了,但没有任何改变。
  • 相信我。它改变了一些东西。您只是在调试方面做得还不够远,无法看到它解决的问题。不要撤消该修复。

标签: c++ sstream


【解决方案1】:

这点逻辑很可疑:

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

}

这将逐个遍历tempLine 中的所有字符,并尝试从ss 中读取整个单词。想一想:对于每个字符,读一个完整的单词。 ss 包含 tempLine 的副本,但除此之外,它们是独立的实体。在字大小的块中读取ss 和在char 大小的块中读取tempLine,字将在循环终止之前很久就用完。而且由于 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_ASSIGMENTS 是用于调整 score 数组大小的任何 OP 的占位符。

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 2012-08-08
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2016-07-17
    • 1970-01-01
    相关资源
    最近更新 更多