从文件中读取浮点数并将它们存储到数组C ++中

时间:2015-08-21 08:50:36

标签: c++ arrays file

我正在尝试将一些浮点数从文件存储到数组中,以便进一步使用它们。到现在为止,我正在测试我的函数以查看它是否存储了某些东西,但我在输出中得到的只是一个零值的数组。 我的文件有很多行,每行写入200个数字。 我的问题是如何正确地将文件中的所有数字加载到数组中。谢谢!

这是我的代码:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
void LoadCoefs(const char* input, float output[], int size );
int main(int argc, const char * argv[])
{
    float* coefs;
    coefs = new float[200];
    LoadCoefs("CoefsFile", coefs, 200);
    for(int i=0; i<200;i++)
    {
        cout<< coefs[i] <<"\n";
    }
    delete [] coefs;
    return 0;
}

void LoadCoefs(const char* input, float output[], int size )
{

    ifstream inp;
    inp.open(input);
    for(int i=0; i<size; i++)
    {
        inp >> output[i] ;

    }
    inp.close();

}

2 个答案:

答案 0 :(得分:1)

在我的电脑上,这有效。 你检查了你的ifstream吗?

ifstream inp(input),
if (!inp) {
  std::cout << "Failed to open the file";
}

另一件事,使用std::arraystd::vector而不是C风格的数组和指针。

答案 1 :(得分:0)

我发现了什么问题。

1)我用绝对路径替换了文件的相对路径。

2)我的号码用逗号分隔。删除逗号后,我的数组加载了我的文件中的数字。

相关问题