【问题标题】:Reading float numbers from a file and storing them into an array C++从文件中读取浮点数并将它们存储到数组 C++
【发布时间】:2015-08-21 08:50:35
【问题描述】:

我正在尝试将文件中的一些浮点数存储到数组中,以便进一步使用它们。到目前为止,我正在测试我的函数以查看它是否存储了一些东西,但我在输出中得到的只是一个带有零的数组。 我的文件有很多行,每行有 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();

}

【问题讨论】:

    标签: c++ arrays file


    【解决方案1】:

    在我的电脑上可以。 你检查过你的 ifstream 了吗?

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

    另外,使用 std::arraystd::vector 代替 C 样式的数组和指针。

    【讨论】:

    • 这很奇怪,我设置了条件来检查它是否也打开了文件。但我在输出控制台中获得的只是 200 个零值。
    • 嗯,我使用的是 Mac 和 XCode,我不太熟悉他格式化文本的方式。但不适用于 .txt 文件。几天前我试过(用另一个例子)让文件不带扩展名,没关系。
    • 好的。仔细检查了我的输出控制台,问题出在我的文件中。打开失败。其余 200 个零来自分配 coef 的动态内存。
    【解决方案2】:

    我找到了问题所在。

    1) 我已将文件的相对路径替换为绝对路径。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2013-01-07
      • 2012-11-27
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多