Arguments

1. การรับ Argument Input ผ่าน command line

myarg.cpp
#include <iostream>
using namespace std;

int main( int argc, char** argv )
{
    cout << "You have entered " << argc << " arguments: " << endl;
    for (int i = 0 ; i < argc ; i++) {
    cout << "argv " << i << " is: " << argv[i] << endl;
    }
    return 0;
}

จากข้างบนตัว argc เป็นตัวแปรเก็บจำนวนของอาร์กิวเม้นต์ และ argv เป็นตัวแปรชนิดอะเรย์ที่เก็บข้อความแต่ละอาร์กิวเม้นต์

หลังจากนั้นทำการคอมไพล์โปรแกรม และทดสอบการเรียกโปรแกรมพร้อมการส่งผ่านค่าอาร์กิวเม้นต์ดังนี้

$ g++ myarg.cpp -o myarg
$ ./myarg arg1 arg2

ผลลัพธ์จากการรันโปรแกรม myarg

Output
You have entered 3 arguments: 
argv 0 is: ./myarg
argv 1 is: arg1
argv 2 is: arg2

2. ตัวอย่างการรับค่า argument จาก ข้อความ --เป็น-->ตัวเลข

temp_converter.cpp
// Celsius to Fahrenheit conversion

#include <iostream>
using namespace std;
 
float celsius;
float fahrenheit;

int main( int argc, char** argv)
{

    if (argc != 2){
        fprintf(stderr, "usage: ./temp_converter <Celsius's value>\n");
        exit(1);
    }
    celsius = atof(argv[1]); //  // assign value to addr stored in celsius
    fahrenheit = celsius * 1.8 + 32; // Celsius to Fahrenheit conversion

    cout << "It's " << fahrenheit << " fahrenheit" << endl; 
    
    return 0;
}

หลังจากนั้นทำการคอมไพล์โปรแกรม และทดสอบการเรียกโปรแกรมพร้อมการส่งผ่านค่าอาร์กิวเม้นต์ดังนี้

$ g++ temp_converter.cpp -o temp_converter
$ ./temp_converter
usage: ./temp_converter <Celsius's value>
$./temp_converter 32

ผลลัพธ์จากการรันโปรแกรม temp_converter

It's 89.60 fahrenheit

Last updated

Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University