# Arguments

<div align="center"><figure><img src="https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MClo3nC-1US0rbK8Qau%2Fuploads%2FZ0U2Hlm4b5Rf9uBFhmcY%2Fimage.png?alt=media&#x26;token=dcb99acb-0ff6-495c-9776-8a436b67e65b" alt=""><figcaption><p>Ref: <a href="https://www.programiz.com/cpp-programming/default-argument">https://www.programiz.com/cpp-programming/default-argument</a></p></figcaption></figure></div>

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

{% code title="myarg.cpp" %}

```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;
}

```

{% endcode %}

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

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

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

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

{% code title="Output" %}

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

{% endcode %}

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

{% code title="temp\_converter.cpp" %}

```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;
}
```

{% endcode %}

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

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

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

```c
It's 89.60 fahrenheit
```
