繁体   English   中英

在 C++ 中解析命令行 arguments

[英]Parsing command line arguments in C++

下面是我试图解决的示例代码。 使用 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 个 arguments ,例如学生姓名和级别。 就像是

$./calculator --student-name 丽塔 --level 3

而我的 output 应该类似于标记*级别。 我尝试单独编写一小段代码,但我没有做对。

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;
}

任何人都可以在这方面指导我。 谢谢!

例如在这个 if 语句中

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

(您错误地使用了本地(块范围)变量argv的限定名称std::argv[1]而不仅仅是argv[1] )比较了两个地址:第一个是argv[1]指向的字符串argv[1]第二个是字符串文字"--student-name"的第一个字符的地址。 由于这是两个不同的对象,因此它们的地址不同,

To compare C strings you need to use the standard C function strcmp declared in the header <cstring> .

例如

#include <cstring>

//...

if( std::strcmp( argv[1], "--student-name" ) == 0 )
// ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM