在 C++ 程式中解析命令列引數
程式執行時,可以從命令列向 C++ 程式傳遞一些值。這些值稱為命令列引數,很多情況下它們對你的程式十分重要,尤其當你想要從外部控制你的程式,而不是在程式碼中對這些值進行硬編碼時。
命令列引數透過 main() 函式引數來處理,其中 argc 表示傳遞的引數數量,而 argv[] 是指向傳遞給程式的每個引數的指標陣列。以下是一個簡單的示例,用來檢查是否從命令列提供了任何引數並相應採取行動 −
示例程式碼
#include <iostream> using namespace std; int main( int argc, char *argv[] ) { if( argc == 2 ) { cout << "The argument supplied is "<< argv[1] << endl; } else if( argc > 2 ) { cout << "Too many arguments supplied." <<endl; }else { cout << "One argument expected." << endl; } }
輸出
$./a.out testing The argument supplied is testing
輸出
$./a.out testing1 testing2 Too many arguments supplied.
輸出
$./a.out One argument expected
廣告