gpt4 book ai didi

c++ - 两行后 fstream 没有从文本文件中读取

转载 作者:太空宇宙 更新时间:2023-11-04 16:25:18 25 4
gpt4 key购买 nike

我正在为这部分代码苦苦挣扎,无论我如何尝试,我都无法在两行后将其读入记录

文本文件包含

Mickey Mouse 12121Goofy24680Andy Capp01928Quasi Modo00041end

and the code is

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

}

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

最佳答案

问题在于:

textfile>>credentials[row].number;

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

textfile>>credentials[row].number;

尝试读取 "Goofy"进入 int失败并设置 textfile 的故障位stream 意味着所有进一步的读取尝试都失败了。检查返回值以检测失败:

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> 它将根据需要增长。

关于c++ - 两行后 fstream 没有从文本文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12528744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com