只有当输入文件确实包含要读取的另一个值时,我才能让getline(variable,n)运行



我意识到这个问题的措辞可能有点奇怪,但请允许我更好地解释自己。输入文件可能包含由6个等级组成的多行。。。或至少5个等级。

所以一个文件可能看起来像这样:

90 85 72 95 83 96
97 69 29 0 39 69

当每行有6个等级时,我的代码运行得很好。

while(!fin.eof())
{
fin.getline(student[student_count].grade1, 4, ' ');
fin.getline(student[student_count].grade2, 4, ' ');
fin.getline(student[student_count].grade3, 4, ' ');
fin.getline(student[student_count].grade4, 4, ' ');
fin.getline(student[student_count].grade5, 4, ' ');
fin.getline(student[student_count].grade6, 4);
...
}

不过,只要文件一行中有5个等级,就会崩溃,这是有道理的。示例:

90 85 72 95 83 
97 69 29 0 39 69

我想不出避免这种情况的办法。我在想一个尝试性的陈述,但我似乎无法做到。

附加信息:这些文件确实包含了年级前的名字和姓氏,所以我无法计算每行中的字符数来解决问题。由于如果我说chars<10左右。

注意:我不允许使用字符串库。。。

你可以试试

std::string linefromfile = "90 85 72 95 83"; // parse and save the line here
std::istringstream buffer( linefromfile );
std::string token;
while( std::getline( buffer, token, ' ' ) ) // split the value with whitesaces
{
std::cout << token << std::endl;
}

最新更新