fstream不会在两行后从文本文件中读取

use*_*319 0 c++ console fstream

我正在努力解决这部分代码,无论我尝试什么,我都不能让它读取两行之后的记录

文本文件包含

Mickey Mouse 
12121
Goofy
24680
Andy Capp
01928
Quasi Modo
00041
end

而代码是

#include<iostream>
#include<string.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
#include<conio.h>
#include<fstream>
#include<string>
using namespace std;

struct record          
{               
char name[20];
int number;
 };



void main()
{


record credentials[30];
    int row=0; 
fstream textfile;//fstream variable
textfile.open("credentials.txt",ios::in);
textfile.getline (credentials[row].name,30);
//begin reading from test file, untill it reads end
while(0!=strcmp(credentials[row].name,"end"))
{ 

    textfile>>credentials[row].number;

    row++;
    //read next name ....if its "end" loop will stop
    textfile.getline (credentials[row].name,30);
}
textfile.close();

}
Run Code Online (Sandbox Code Playgroud)

记录只采取前两行,其余的是空的任何想法?

hmj*_*mjd 5

问题是:

textfile>>credentials[row].number;
Run Code Online (Sandbox Code Playgroud)

而不消耗换行符.随后调用textfile.getline()读取空行和下一行:

textfile>>credentials[row].number;
Run Code Online (Sandbox Code Playgroud)

尝试读"Goofy"int哪个失败并设置textfile流的failbit 意味着所有进一步的读取尝试失败.检查返回值以检测故障:

if (textfile >> credentials[row].number)
{
    // Success.
}
Run Code Online (Sandbox Code Playgroud)

我不完全确定程序如何结束,因为"end"永远不会被读取但我怀疑它结束异常,因为没有机制来防止超出credentials数组的末尾(即没有row < 30作为循环终止条件的一部分).


其他: