C++ sstream 跳过文件中的前三个输入
C++ sstream skipping first three inputs from a file
我需要打开这种格式的文件
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] != ' '; 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
这个逻辑是可疑的:
for (int i = 0; tempLine[i] != ' '; 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 的占位符。
相关文章:
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口
- 如何知道n!是否可以表示为三个连续数字的乘法?
- 我有三个 getline,但是一旦编译,输入就太多了
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 当我输入 3 个偶数时,它表明我输入了 4
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 异常处理:如果用户输入不是三个特定字符之一
- 在由空间隔开的线中输入三个整数
- 创建一个程序,要求用户输入两个数字,并有三个可能的答案.代码未编译.数字(作为int)
- 当我在程序中输入第二个值时,它将我带到第三值,而无法正确执行
- 我试图显示我输入的三个值中最大和最小的数量
- 如何在C++中从三个不同的txt文件中获取输入
- 程序在开始输入第三个信息后停止
- C++ sstream 跳过文件中的前三个输入
- 为什么这个程序的结果是三个十进制数"597, 295, 295,"输入两个十六进制数"255 127<enter>"
- 读取文件输入的第三个字(c++)
- 输入三个数字,并在c++中确定最高和最低的数字