简体   繁体   中英

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?

I already have some code that dose this but its specific to the function and I cannot use it elsewhere.

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

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. 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. 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? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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