从文件(C++)中读取项目时出现问题

Having trouble reading items from a file (C++)

本文关键字:项目 问题 读取 文件 C++      更新时间:2023-10-16

因此,我在获取文本文件中的最后一项以读入字符串对象时遇到问题。

我创建了一个名为"Car"的类,我应该从文件中读取"Car"对象的所有参数,但它不会注册最后一个。

ifstream对象是"数据"

变量为:

string carType;
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;

文本文件中的行读作:

汽车CN 819481维修错误无

这就是我现在拥有的:

getline(data, ignore); // ignores the header line
data >> carType >> reportingMark >> carNumber >> kind >> loaded;
while (data.peek() == ' ') // this and the next lines were the suggestions of the teacher to bypass the spaces (of which there are more than it will display here)
   data.get();
getline(data, destination);

因此,它将读取除"目的地"部分之外的所有内容。

问题出在这部分:

data >> carType >> reportingMark >> carNumber >> kind >> loaded;

在这里,您尝试从流中派生一个布尔变量loaded。你希望阅读false能奏效,但事实并非如此。它只接受01

相反,未能读取布尔变量将切换流的err位,这使得读取之后的所有其他内容都失败。

为了检查这一点,如果您在该行之后执行data.peek(),您将收到一个-1,表示没有有效的输入。

要解决此问题,您需要将信息存储方式更改为存储0/1而不是true/false,或者更好:

读取数据前执行:data << boolalpha。这将使流将true/false解释为0/1

检查所有IO操作的返回值总是很好的。如果您添加错误检查,您可能能够找到问题并找到解决方案。

if (!getline(data, ignore)) // ignores the header line
{
   std::cerr << "Unable to read the headern";
   exit(EXIT_FAILURE);
}
if ( !(data >> carType >> reportingMark >> carNumber >> kind >> loaded))
{
   std::cerr << "Unable to read the datan";
   exit(EXIT_FAILURE);
}
while (data.peek() == ' ') // this and the next lines were the suggestions of the teacher to bypass the spaces (of which there are more than it will display here)
   data.get();
if ( !getline(data, destination) )
{
   std::cerr << "Unable to read the rest of the linen";
   exit(EXIT_FAILURE);
}

代码似乎是正确的;除了我认为没有必要放

while(data.peek()=='')data.get();

getline(数据,目的地);

部分读取目的地。相反,您可以简单地将其读取为数据>>目的地。此外,通过检查,确保您的输入文件正确打开

if(data.isOpen()){//cout something}

我希望这能有所帮助!:)

给你的"ifstream"对象一个while循环怎么样,比如这个

    ifstream ifstreamObject;
        ifstreamObject.open("car.txt");

cout << "carType"<< ' '<< "reportingMark" << ' '<< "carNumber" <<' '<< "kind" <<' '<< "loaded"<<' '<<"destination"<< endl;
           while(ifstreamObject >> carType >> reportingMark >> carNumber >> kind >> loaded >> destination )
           {       cout <<"---------------------------------------------------------------------------"<<endl;
                   cout << carType<< ' '<< reportingMark << ' '<< carNumber <<' '<< kind <<' '<< loaded<<' '<<destination<< endl;
           }

如果我是你,我会尝试用strtok函数读取文件。

如果你想,你可以阅读这篇文章了解更多信息strtok函数

我最近完成了这项任务,我使用了strtok,因为它允许将文件的每一行拆分为单词列表。此外,它允许您避免分配标点符号,如空格等。(所以我发现它非常有用)

我的例子:我想从文件中读取一些角色数据,比如种族、职业、命中率、攻击和防御。

我文件的每一行看起来都是这样的:人类/士兵/15/7/7

因此,我定义了一个存储strtok函数返回值的char指针和一个存储读取单词的char指针,直到找到之前考虑过的分隔符。(在本例中:"/")

char* position = strtok(file, '/');
char* character_info = new char[size];

因此,将该行存储在characterinfo中,并在每次迭代中检查位置值,直到读取完文件为止。

while(position != NULL){
  // store position value
  // call again strtok
}

我希望它会有帮助

干杯