C 编程从外部输入文件定义数组大小

c++ programming define array size from the external input file?

本文关键字:数组 文件定义 输入 编程 从外部      更新时间:2023-10-16

我想从外部输入定义数组大小。

我创建像这样的代码

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
void loadIt(int[],int);//loadIT prototype
int main()
{   
    ofstream outfile("C:\sir.txt");
    if (!outfile){
    cerr << "Output file could not be opened" << endl;
    exit(1);}
    outfile << setiosflags(ios::fixed|ios::showpoint);
    outfile << setprecision(3);
    outfile << setiosflags(ios::fixed|ios::showpoint);
    outfile << setprecision(3);
    const int arraySize = 20; //here i want the input from the external file
    int a[arraySize];

     loadIt(a, arraySize);//call to loadIT
}

我想从外部文件定义数组大小..plz帮助我

不确定您想要什么,但是以下可能会有所帮助:

std::ifstream in("C:\input.txt");
int size;
in >> size;
std::vector<int> a(size);

假设input.txt类似于

42
// Possible other values.

内置数组类型的大小固定,因此您只能使用编译时常数来指定大小。您需要一个动态数组,该数组由std::vector提供:

#include <vector>
const int arraySize = read_array_size_from_wherever();
std::vector<int> a(arraySize);
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
    const char * fn = "stat.c";
    struct stat buf;
    stat ( fn, &buf );
    std::cout << "File size: " << buf.st_size << std::endl;
    int * a = new int[buf.st_size];
    // Do your processing
    delete[] a;
    return ( 0 );
}