繁体   English   中英

我该如何创建任何在以后的代码中定义大小的数组?

[英]how do i go about creating any array that i define the size for later in the code?

我需要创建两个数组,这些数组的大小反映了我加载到程序中的两个文件中数据的大小。 这些数组然后需要由同一解决方案中的其他.cpp / .h文件访问,我该怎么做呢?

我已经有一些代码可以解决这个问题,但是它特定于该函数,因此我无法在其他地方使用它。

ReadFunction.h

#include <string>
#include <fstream>
#include <iostream>

static std::string read_file(const char* filepath)
{
    FILE* file = fopen(filepath, "rt");
    fseek(file, 0, SEEK_END);
    unsigned long length = ftell(file);
    char* data = new  char[length + 3];
    memset(data, 0, length + 1);
    fseek(file, 0, SEEK_SET);
    fread(data, 1, length, file);
    fclose(file);

    std::string result(data);
    delete[] data;
    return result;

}

Main.cpp的

#include<iostream>
#include "Headers/ReadWFunction.h"


int main(void)
{
    std::string file = read_file("Wally_grey.txt");
    std::cout << file << std::endl;

    system("PAUSE");
    return 0;
}

这段代码可以工作并加载到文件中,然后将其写入控制台,但是我需要对两个不同大小的文件执行两次,然后将它们加载到double类型的一维数组中,然后与另一个.cpp中的一个进行比较。文件。 但是我不知道该怎么做,因为我需要声明一个数组,但不给它一个大小,直到文件中加载了IV,因此知道了数组的所需大小。 另外,还需要通过一个名为compare.cpp的单独的.cpp文件访问这些数组,我是否在readFunctions.h文件中声明了这些数组并将它们公开,还是在其他地方声明了它们? 我对这些东西还很陌生,因此我们将不胜感激。

这是一个从文件中读取double并将其作为向量返回的函数

static std::vector<double> read_file(const char* filepath)
{
    std::vector<double> v;
    std::ifstream file(filepath);
    double x;
    while (file >> x)
        v.push_back(x);
    return v;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM