c++ - 用C++将数据读入双数组

标签 c++ boost datareader

这是我的问题。我有一些维度不断变化的二维数据,我想读入一个二维 double 组。此外,文件中有些地方不是数字而是“NaN”,我想将其替换为零。到目前为止,我的代码可以正常工作,但我只能读取整数。也许你可以帮我把它读成 double ?

这是我到目前为止得到的:

void READER(char filepath [], int target [129][128])
{

    //----------------------------       header double & int

    int rowA = 0;
    int colA = 0;

    std::string line;
    std::string  x;


    std::cout << "reading file: " << filepath << "\n";
    std::cout << std::endl;

    std::ifstream fileIN;
    fileIN.open(filepath);

    if (!fileIN.good())
    std::cerr << "READING ERROR IN FILE: " << filepath << std::endl;



    while (fileIN.good())
    {
        while (getline(fileIN, line))
        {
            std::istringstream   streamA(line);
            colA = 0;
            while (streamA >> x)
            {

                boost::algorithm::replace_all(x, "NaN", "0"); 

                boost::algorithm::replace_all(x, ",", "");            //. rein


                // std::cout << string_to_int(x) << std::endl;

                target [rowA][colA]   =  string_to_int(x);
                colA++;

            }
            rowA++;
            if(rowA%5 ==0)
            {
                std::cout << "*";
            }
        }
    }



    std::cout << " done." <<std::endl;


}

这会将文件写入“目标”。 int 的函数字符串如下所示:

int string_to_int (const std::string& s)
{
    std::istringstream i(s);
    int x;
    if(!(i >> x))
        return 0;
    return x;

}

在这里您可以找到一些示例数据: enter image description here

最佳答案

“正是,这就是我想用 boost::algorithm::replace_all(x, ",", ""); 行将 , 替换为 。

使用以下函数转换为任何类型,比如 double :-

template <typename T>
  T StringToNumber ( const std::string &Text )
  {
     std::istringstream ss(Text);
     T result;
     return ss >> result ? result : 0;
  }

调用方式:

boost::algorithm::replace_all(x, ",", ".");         // Change , to .
std::cout << StringToNumber<double>(x) << std::endl;

或者

你可以简单地使用 boost::lexical_cast

std::cout<<boost::lexical_cast<double>( x )<<std::endl;

确保你有一个 double二维数组

关于c++ - 用C++将数据读入双数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009912/

相关文章:

C++ 隐式函数调用

类中的 C++ 后台线程 - 实例范围

c++ - 段错误核心在 pthread_join 之前转储

c++ - 在 [现代] C++ 中通过 N 个变量进行范围/循环

sql-server - SQL Server 锁定的 DataReader 行为

asp.net - 在 ASP.NET (VB) 上使用 DataReader 返回上一行

c++ - 如何在 C++ 中使用指针从数组中删除最后一个元素?

c++ - 如何用不同类型的迭代器填充 vector ?

用于 boost : asio 的 c++ 文件

c# - datareader 失败但不引发异常 c#