通过命令参数将文件传递到数组中

问题描述 投票:-4回答:1

所以我试图将命令行参数传递给我的int main中的数组像这样$< .\program nums.txt 8,但由于我对C ++代码的了解,我遇到了很多错误并陷入了僵局。 (我是相对较新的编码器)。非常感谢您的帮助。

 int main(int argc,char *argv[])
    {
        string arg2=" ";
        arg2 = argv[2];
        int size; 
        size=stod(arg2);
        string arr[size];
        string file = argv[1];
        ifstream infile;
        if (getline infile.open(file))
        {
            int arr[size],val;
            for(int i=0;i<size;i++)
            {
                getline(file, arr[i]);
            }
        }
    int choice = 5,value,position,target ;
c++ arrays fstream argv argc
1个回答
0
投票

您的问题中有很多错别字。我仍然认为该代码可以为您提供帮助:

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

int main(int argc, char *argv[]) {
    int size = atoi(argv[2]);
    std::vector<std::string> arr(size);
    std::ifstream infile(argv[1]);
    if (not infile) {
        std::cerr << "File not found!" << std::endl;
        return -1;
    }
    for (int i = 0; i < size; i++)
        if (infile)
            getline(infile, arr[i]);
        else {
            std::cerr << "Not enough lines in the file!" << std::endl;
            return -2;
        }
    // do rest of your things here ...
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.