所以我试图将命令行参数传递给我的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 ;
您的问题中有很多错别字。我仍然认为该代码可以为您提供帮助:
#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;
}