【问题标题】:Parsing command line arguments in C++在 C++ 中解析命令行参数
【发布时间】:2020-06-14 17:55:10
【问题描述】:

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

#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

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

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 字符串,您应该使用函数 strcmp。
  • “我没有做对。” 不是可接受的问题陈述。详细说明您的问题。

标签: c++ c-strings strcmp command-line-arguments


【解决方案1】:

例如在这个 if 语句中

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

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

要比较 C 字符串,您需要使用标头 &lt;cstring&gt; 中声明的标准 C 函数 strcmp

例如

#include <cstring>

//...

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

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 1970-01-01
    • 2017-08-31
    • 2010-10-26
    • 2021-07-27
    相关资源
    最近更新 更多