在C ++中解析命令行参数

问题描述 投票:0回答:1

下面是我尝试解决的示例代码。使用stl映射计算学生的成绩。

#include <iostream>
#include <iterator>
#include <map>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
#include <string>

using namespace std;

int main()

{

typedef map<string, int>mapType;
mapType calculator;

int level;
string name;

//Student and Marks:
calculator.insert(make_pair("Rita", 142));
calculator.insert(make_pair("Anna", 154));
calculator.insert(make_pair("Joseph", 73));
calculator.insert(make_pair("Markus", 50));
calculator.insert(make_pair("Mathias", 171));
calculator.insert(make_pair("Ruben", 192));
calculator.insert(make_pair("Lisa", 110));
calculator.insert(make_pair("Carla", 58));

mapType::iterator iter = --calculator.end();
calculator.erase(iter);


for (iter = calculator.begin(); iter != calculator.end(); ++iter) {
    cout << iter->first << ": " << iter->second << "g\n";
}
cout << "Choose a student name :" << '\n';
getline(cin, name);

iter = calculator.find(name);
if (iter == calculator.end())
    cout << "The entered name is not in the list" << '\n';
else
    cout << "Enter the level :";
cin >> level;

cout << "The final grade is " << iter->marks * level << ".\n";

}

现在,我想假设我的程序接受2个参数,例如学生姓名和水平。像

之类的东西

$。/ calculator --student-name Rita --level 3

而且我的输出应该是mark * level。我尝试单独编写一小段代码,但是我做得不好。

using namespace std;

const char* studentName ="--student-name";
int main(int argc,char* argv[])
{
int counter;
if(argc==1)
    printf("\nNo Extra Command Line Argument Passed Other Than Program Name");
if(argc>=2)
{

        printf("%s\n",argv[1]);
                if(std::argv[1] == "--student-name")
                {
                    printf("print nothing");
                }
                else if(argv[1]=="--level")
                {
                    printf("%s",argv[2]);
                }

}
return 0;
}

任何人都可以指导我。谢谢!

c++ c-strings strcmp command-line-parsing
1个回答
1
投票

例如在此if语句中

if(std::argv[1] == "--student-name")

((您错误地使用了局部(块作用域)变量std::argv[1]的限定名称argv,而不仅仅是argv[1]),这里比较了两个地址:第一个是[C0所指向的字符串],第二个是字符串文字argv[1]的第一个字符的地址。由于这是两个不同的对象,因此它们的地址也不同,

要比较C字符串,您需要使用在标题"--student-name"中声明的标准C函数strcmp

例如

<cstring>
© www.soinside.com 2019 - 2024. All rights reserved.