执行项目分配,我似乎无法使命令标志正常工作。一直在寻找帮助,但在这个问题上找不到多少。我的老师从未解释过这是什么或怎么做,所以我只是根据我在网上找到的东西做事。任何解决方案或解释都将不胜感激。
#include<fstream>
#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
int main(int argc, char *argv[])
{
if(argc != 0)
{
for (int i = 0; i < argc; i++)
{
ifstream file1(argv[i]);
string arg1 = argv[i];
int counter = 0;
int counter2 = 0;
string longest, word;
char letter;
vector<string> arrayWord, numString;
vector<int> largestNum;
stringstream ss;
if(file1.is_open() == false)
{
cout << "File Not Found\n";
continue;
}
else if (arg1 == "c")
{
while (!file1.eof())
{
letter = file1.get();
if(letter != ' ')
{
word = word + letter;
letter = file1.get();
counter++;
}
else if (letter == ' ')
{
arrayWord[counter2] = word;
largestNum[counter2] = counter;
ss << largestNum[counter2];
numString[counter2] = ss.str();
counter2++;
word.clear();
}
}
longest = arrayWord[0];
for (int i = 0; i <= counter2; i++)
{
if (largestNum[counter2] < largestNum[counter2 + 1])
{
longest = arrayWord[counter2 + 1] + "(" + numString[counter2 + 1];
}
else if (largestNum[counter2] == largestNum[counter2 + 1])
{
longest = longest + "(" + (numString[counter2 + 1]) + ", " + arrayWord[counter2 + 1] + "(" + numString[counter2 + 1];
}
else
{
longest = arrayWord[counter2] + "(" + numString[counter2];
}
}
cout << longest << endl;
continue;
}
else
{
cout << "Program is running with an invalid command" << endl;
continue;
}
}
}
return 0;
}
答案 0 :(得分:0)
在我看来,您试图对命令行中的每个项目运行相同的功能。
我强烈建议将实际功能拆分为单独的函数(process_file
),然后循环遍历参数并运行您的功能。
注意:我们从argv[1]
开始,因为argv[0]
是用户在命令行上输入的任何内容,以获取您的程序。这通常类似于./my-program
,假设用户键入了./my-program file1.txt file2.txt
以下示例将在每个文件上运行您的功能。
int main(int argc, char ** argv){
int i;
for ( i = 1; i < argc; i++){
printf("Processing \"%s\":\n", argv[i]);
process_file(argv[i]);
}
}