0

我正在努力处理这部分代码,无论我尝试什么,我都无法在两行之后将其读入记录

文本文件包含

米老鼠
12121
高飞
24680
安迪·卡普
01928
准莫多
00041
结尾

代码是

#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();

}

记录只取前两行,其余的都是空的有什么想法吗??

4

1 回答 1

5

问题是:

textfile>>credentials[row].number;

同时不消耗换行符。随后的调用textfile.getline()读取一个空行和下一个:

textfile>>credentials[row].number;

尝试读取失败并设置流"Goofy"的失败位意味着所有进一步的读取尝试失败。检查返回值以检测失败:inttextfile

if (textfile >> credentials[row].number)
{
    // Success.
}

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


其他:

  • 而不是使用固定大小char[]将名称读入您可以使用std::getline()

    #include <string>
    
    struct record
    {
        std::string name;
        int number;
    };
    
    if (std::getline(textfile, credentials[row].name))
    {
    }
    
  • record[]您可以使用std::vector<record>将根据需要增长的而不是使用固定大小。

于 2012-09-21T10:32:15.113 回答