如何在 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
廣告