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

Command line arguments ใน C/C++


สามารถส่งค่าจาก command line ไปยังโปรแกรม C ตอน execute ได้ ค่าเหล่านี้เรียกว่า command line arguments สำคัญเมื่อต้องการควบคุมโปรแกรมจากภายนอกแทน hard code

Command line arguments จัดการด้วย main() function arguments argc คือจำนวน arguments argv[] คือ pointer array ชี้ไปแต่ละ argument

ตัวอย่าง

#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");    } }

ผลลัพธ์

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

ผลลัพธ์

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

ผลลัพธ์

$./a.out One argument expected

argv[0] เก็บชื่อโปรแกรม argv[1] ชี้ argument แรก *argv[n] คือ argument สุดท้าย หากไม่มี arguments argc = 1 ส่งหนึ่ง argument argc = 2

ส่ง arguments คั่นด้วย space หาก argument เองมี space ใช้ double quotes "" หรือ single quotes '' ตัวอย่างพิมพ์ program name และส่ง argument ใน quotes:

ตัวอย่าง

#include <stdio.h> int main( int argc, char *argv[] ) {    printf("Program name %s\n", argv[0]);    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");    } }

ผลลัพธ์

$./a.out "testing1 testing2" Progranm name ./a.out The argument supplied is testing1 testing2