1

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

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

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;

}

在这里您可以找到一些示例数据: 在此处输入图像描述

4

1 回答 1

1

“没错,这就是我想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二维数组

于 2013-09-25T16:32:47.577 回答