cpp:argc和argv的应用

argc和argv的应用

 

 

 

一、argc和argv的说明(linux):

 

// file_name=app_test.cpp  
// application_name=app_test

int main(int argc, char* argv[]) {   // body of function } // 运行程序;参数:hello, world! ./app_name hello, world!

  

 

参数说明:

 

1、argc和argv:在“某程序的外部”,给该程序“传递参数”;

 

2、argc:代表传入程序的参数个数;参数之间分隔符包括“空格/tab”;argc初始值为“0”;

                1.1、argc = 2

 

3、argv:是一个字符的指针数组,每个数组保存“传入的参数”;argv[0]的值为“应用程序名字”,argv[1]的值为传入的第一个参数的值;...,argv[k]的值为传入的第k个参数的值。

                2.1、argv[0]=app_name

                2.2、argv[1]=hello,

                2.3、argv[2]=world!

 

 

 

 

二、应用示例

 

 

[root@rockylinux tmp]# uname -a
Linux rockylinux 4.18.0-348.7.1.el8_5.x86_64 #1 SMP Tue Dec 21 19:02:23 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
[root@rockylinux tmp]# ./cpp_test  hello_word  hello_houdini19  hello,  china!
Hello, World!
OS: List Input Parameters...
argc=5
argv[0]=./cpp_test
argv[1]=hello_word
argv[2]=hello_houdini19
argv[3]=hello,
argv[4]=china!
[root@rockylinux tmp]# cat cpp_test.cpp 
#include<iostream>


using namespace std;


void msg()
{
        cout << "Hello, World!" << endl;
}


void input(int count, char* array[])
{
        cout << "OS: List Input Parameters..." << endl;
        cout << "argc=" << count << endl;

        for(int i=0; i<count; i++)
        {
                cout << "argv[" << i << "]=" << array[i] << endl;
        }
}


// test functions

int main(int argc, char* argv[])
{
        msg();
        input(argc, argv);

        return 0;
}
[root@rockylinux tmp]#

  

 

 

本文由lnlidawei(https://www.cnblogs.com/lnlidawei)原创或整理,转载请注明出处。
原文地址:https://www.cnblogs.com/lnlidawei/p/15765169.html