Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธี Parse Command Line Arguments ใน C++

บทนำ

สามารถส่งค่าจากคอมมานด์ไลน์ไปยังโปรแกรม C++ ขณะรันได้ ค่าเหล่านี้เรียกว่า command line arguments ซึ่งสำคัญเมื่อต้องการควบคุมโปรแกรมจากภายนอกแทนการ hard-code ค่าในโค้ด

Command line arguments จัดการด้วยอาร์กิวเมนต์ของ 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;
    }
    return 0;
}

ผลลัพธ์

$ ./a.out testing
The argument supplied is testing
$ ./a.out testing1 testing2
Too many arguments supplied.
$ ./a.out
One argument expected.