[英]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.