简体   繁体   English

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

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

I need to create two arrays that have there size reflect the size of the data in two files that I load into the program. 我需要创建两个数组,这些数组的大小反映了我加载到程序中的两个文件中数据的大小。 these arrays need to then be accessed by other .cpp/.h files within the same solution how would I go about doing this? 这些数组然后需要由同一解决方案中的其他.cpp / .h文件访问,我该怎么做呢?

I already have some code that dose this but its specific to the function and I cannot use it elsewhere. 我已经有一些代码可以解决这个问题,但是它特定于该函数,因此我无法在其他地方使用它。

ReadFunction.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 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;
}

This code works and loads in a file and then writes it to the console, however I need to do this twice for two different sized files and then load them into 1D arrays of type double to then be compared against one anouther in a different .cpp file. 这段代码可以工作并加载到文件中,然后将其写入控制台,但是我需要对两个不同大小的文件执行两次,然后将它们加载到double类型的一维数组中,然后与另一个.cpp中的一个进行比较。文件。 however I have no idea how to go about this as i would need to declare an array but not give it a size untill iv loaded in the file and therefore know the required size of the array. 但是我不知道该怎么做,因为我需要声明一个数组,但不给它一个大小,直到文件中加载了IV,因此知道了数组的所需大小。 Also the arrays need to be accessed by a seperate .cpp file called compare.cpp, do I declare the arrays in the readFunctions.h file and have them public or do i declare them elsewhere? 另外,还需要通过一个名为compare.cpp的单独的.cpp文件访问这些数组,我是否在readFunctions.h文件中声明了这些数组并将它们公开,还是在其他地方声明了它们? Im farly new to this stuff so any help would be appreciated. 我对这些东西还很陌生,因此我们将不胜感激。

Here's a function that reads doubles from a file and returns them as a vector 这是一个从文件中读取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