【问题标题】:Ifstream not retrieving data using array in C++Ifstream不使用C++中的数组检索数据
【发布时间】:2019-05-04 07:39:57
【问题描述】:

我一直在尝试使用 ifstream 从 employee-info.txt 读取数据并将其存储在一个数组中,但它没有读取任何内容。

我的代码的主要目标是,每次它能够读取employee-info.txt 中的值时,它都会循环并且整数变量valueChecker 将加一。循环完成后,将返回 valueChecker 的值,以确定从employee-info.txt 中检索到多少字符串。根据employee-info.txt的内容,它应该返回一个8的int,但它只返回一个0的int,即初始化值。

我还通过调试器进行了检查,记录数组没有从文件中读取任何内容。我已经检查了文件的地址,它是正确的。

这是Employee.h中的代码:

#pragma once
#include<string>
#include<iostream>

class Employee
{
public:
   struct EmployeeRecord {
     static const int recordSize = 100;
     static const int fieldSize = 4;
     std::string record[recordSize][fieldSize];
   };

public:
   Employee();
   ~Employee();
   int employeeDataChecker();
   void employeeWriteData();
   void employeeDisplayData();
   EmployeeRecord& employeeReturnRecordArray();

private:
   EmployeeRecord emp_record;

};

Employee.cpp:

#include "Employee.h"
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>

int Employee::employeeDataChecker()
{
    //Check if there are data in the employee-info.txt
    EmployeeRecord emp;
    int valueChecker = 0;
    std::ifstream inFile;
    inFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt");
    for (int index = 0; index < emp.recordSize; index++) {
        for (int index2 = 0; index2 < emp.fieldSize; index2++) {
            while (inFile >> emp.record[index][index2]) {
                valueChecker++;
            }
        }
    }
    inFile.close();
    return valueChecker;
}

员工信息.txt:

     ID           Firstname            Lastname                 Sales
      1                 Joe            Satriani             500000.00 

【问题讨论】:

  • 使用inFile.good()检查文件是否正确打开
  • 您不应该将emp 分配给emp_record,还是完全放弃这个本地对象?无论如何,有一个名为employeeDataChecker 的函数打开文件并修改对象是很奇怪的。
  • 嗯...while (inFile &gt;&gt; emp.record[index][index2]) ?如果不对indexindex2 进行任何调整或检查,该内容将驱动到文件末尾。 IE。外面的 for 循环毫无价值。我敢问为什么那里有while 吗?就此而言,为什么没有only 行计数器?一个简单的检测到标准输出的转储应该有助于解释为什么 valueChecker 无论如何都保持为零。

标签: c++ arrays file-io fstream ifstream


【解决方案1】:

是的,首先,您必须检查文件是否正确打开(即 inFile.is_open())。

然后,忘记对字段的迭代并尝试执行以下操作:

int id;
char firstname[64] = { 0 };
char lastname[64] = { 0 };
float sales;

inFile >> id;
inFile.get(firstname, 64, ' ');
inFile.get(lastname, 64, ' ');
inFile >> sales;

如果失败,[inFile >>] 运算符可能返回 false,然后它不会增加 valueChecker。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多