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

Command Line Arguments ใน C

รับค่าจาก Command Line ผ่าน main(int argc, char *argv[])

  • argc: จำนวนอาร์กิวเมนต์ (รวมชื่อโปรแกรม)
  • argv[]: Array ของ String แต่ละอาร์กิวเมนต์

ตัวอย่าง

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc == 2)
        printf("The argument supplied is %s\n", argv[1]);
    else if (argc > 2)
        printf("Too many arguments supplied.\n");
    else
        printf("One argument expected.\n");
    return 0;
}

ผลลัพธ์

$ ./a.out testing
The argument supplied is testing

$ ./a.out testing1 testing2
Too many arguments supplied.

$ ./a.out
One argument expected.