c++ - 如何允许文本文件中丢失数据

标签 c++ vector double

我有一个包含大量数据集的大文件,尽管标记为“--”但仍有一些空白,但出于某种原因未记录数据。其余数据将以 double 形式存储在 vector 中,我的问题是如何获取丢失的数据并将这些丢失的数据存储为零?我的数据文件的片段;

0    29.1     ---
0    65.9     ---
2    56.5     ---
6    19.7    44.3
9    69.8    64.9
11   118.6   64.8
7    35.7    64.1




if (myfile.is_open())
  {
    int count = 0;
    while ( myfile.good() )
    {
      getline (myfile,line);
      /*if (line == "---")
        {
        sun(0.0);
        }*/
      if (count > 6) 
      {

      std::istringstream buffer(line);
            int month;
            double  rain, sun;
            if (buffer >> month >> rain >> sun)
            {
                Weather objName = {month, rain, sun};
                data_weather.push_back(objName);       
            }
      }
      count++;
    }
    myfile.close();

最佳答案

一次读取一行数据作为字符串。检查是否为“--”。如果是则相同的 0.0,如果不是则转换为 double 并保存 double 。

string line;
while (getline(file, line))
{
    if (line == "--")
    {
        save(0.0);
    }
    else
    {
        istringstrleam buf(line);
        double value;
        if (buf >> value)
        {
            save(value);
        }
        else
        {
            error("could not convert value");
        }
    }
}

我正在使用 istringstream 进行从字符串到 double 的转换。

更新

根据问题中有关文件格式的新信息,以下内容应该有效(但它是未经测试的代码)。

string line;
while (getline(file, line))
{
    if (count > 6)
    {
        int month;
        double rain, sun;
        std::string sun_as_string;
        std::istringstream buffer(line);
        if (buffer >> month >> rain >> sun_as_string)
        {
            if (sun_as_string == "--")
            {
                sun = 0.0;
            }
            else
            {
                std::istringstream buffer2(sun_as_string);
                if (!(buffer2 >> sun))
                {
                    // couldn't convert the sun value, so just set to zero
                    sun = 0.0;
                }
            }
            Weather objName = {month, rain, sun};
            data_weather.push_back(objName);       
        }

    }
    ++count;
}

基本思路与之前相同,将太阳值作为字符串读取,如果不是“--”则仅将其转换为 double 值。

关于c++ - 如何允许文本文件中丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879252/

相关文章:

c++ - 将 int 添加到 size_t 的正确方法

c++ - 动态数组到两个函数

c++ - 使用 boost.hana 内省(introspection)结构定义

c++ - 对象如何将自身添加到该对象的类中的 vector ?

c++ - concurrent_vector vs vector with mutex, push_back 线程问题

c# - 将 double 转换为 decimal 还是从 double 构造 "new"decimal 更好?

c++ - linux c++ 如何在特定时间间隔后调用函数

c++ - 对没有比较器或 lambda 函数的 vector 进行排序?

C++ 和 C++11 类静态成员,double 应该使用 "constexpr"而 int 可以是 "const",为什么?

c - 将 double 除以 0 的 double 给出表达式的极限而不是错误