簡體   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