【问题标题】:Incorrect numbers showing up after trying to read data with ifstream尝试使用 ifstream 读取数据后显示不正确的数字
【发布时间】:2017-07-10 06:12:12
【问题描述】:

我有一个文本文件,我正在尝试使用 ifstream 从其中读取几行数据,然后我可以将它们添加到链接列表中。我正在使用老师提供给我的主要课程/功能,所以我没有亲自编写任何内容。我已经编写了一些其他的类来配合它,如果需要的话我可以提供,但是在调试时,一旦主函数开始尝试读取数据,问题就开始了。

#include <iostream>
#include <fstream>
#include "datalogger.h"

using namespace std;

int main(int argc, char** argv) {

datalogger dl;

if (argc != 2) {
    cout << "Usage: " << argv[0] << " <datafile>" << endl;
    exit(0);
}

// Read the data

char* datafile = argv[1];
ifstream infile(datafile);
int timestamp;
double temperature;
double windspeed;

while (!infile.eof()) {
    infile >> timestamp;
    infile >> temperature;
    infile >> windspeed;

    if (!infile.eof()) {
        dl.addData(timestamp, temperature, windspeed);
    }
}

// Output the report
dl.printReport();

return(0);
}

datafile(smallerdata.txt)的内容如下:

1480906168 -226 361
1480906168 -224 270
1480906175 -222 326
1480906179 -218 236
1480906187 -218 145
1480906189 -216 109
1480906189 -212 145
1480906190 -208 153
1480906197 -204 90

第一行的timestamp应该是1480906168,temperature和windspeed应该分别是-226和361。相反,我的调试器在第 24-27 行的断点处暂停时给了我这些值:

timestamp = 0

temperature = 2.1219889530967339e-314

windspeed = 3.184022971431627e-314

这些值到底是从哪里来的?为什么?

【问题讨论】:

标签: c++ io ifstream


【解决方案1】:

我建议您添加检查文件是否已打开,例如:

ifstream infile(datafile);
if (!infile.is_open())
{
    cout << "File " << argv[1] << " cannot be open!" << endl;
    exit(0);
}

并且还要改变for循环的条件,例如:

while (infile.good()) {
    infile >> timestamp;
    infile >> temperature;
    infile >> windspeed;
    // just to simplify debugging
    cout << "timestamp   = " << timestamp << endl
        << "temperature = " << temperature << endl
        << "windspeed   = " << windspeed << endl;
    // your data processing
    if (!infile.eof()) {
         dl.addData(timestamp, temperature, windspeed);
    }
}

【讨论】:

  • 我无法更改主函数中的任何代码,因为它是提供给我们的并且“不可更改”。我粘贴了条件,看起来好像它甚至没有打开文件。如果无法打开文件但我不允许编辑源代码,真的不知道该怎么办。
  • 因此,使用调试器查看该文件是否真正打开,如果没有,请在运行程序时检查您在命令行中提供的文件路径
【解决方案2】:

当文件中有整数值时,为什么要读取双精度值?

double temperature;
double windspeed;

应该是

int temperature;
int windspeed;

【讨论】:

  • ThomasJazz 在 cmets 中对我的回答说,提供的代码 sn-p 无法更改,因此文件样本中表示的所有数据的数据类型可以是 int,但问题不在于数据类型,并且任何十进制表示的整数输入都可以读取到double 或float
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多