美文网首页
(八)C++篇-main函数参数传递

(八)C++篇-main函数参数传递

作者: GoodTekken | 来源:发表于2022-06-19 22:07 被阅读0次

    1,main函数参数传递,测试代码如下:

    #include <iostream>
    using namespace std;
    
    int main(int argc, char **argv)
    {
        //check the count of argument
        if(argc !=3)
        {
            cout<< "you should use three argument!"<<endl;
            return -1;
        }
        
        cout<<"Summation of "<<argv[1]<< " and " << argv[2] << " is " << (atof(argv[1])+atof(argv[2])) <<endl;
        return 0;
    }
    

    输出结果:

    tekken@tekken:~/C++WS$ ./a.out 5 6
    Summation of 5 and 6 is 11
    tekken@tekken:~/C++WS$ ./a.out
    you should use three argument!
    

    2,输出传递给main的实参的值,测试代码如下:

    #include <iostream>
    using namespace std;
    
    int main(int argc,char **argv)
    {
        cout << "argument passed to main():"<<endl;
        for(int i = 0;i!= argc;++i)
        {
            cout<<argv[i]<<endl;
        }
        return 0;
    }
    

    输出结果:

    tekken@tekken:~/C++WS$ ./a.out 5 6
    argument passed to main():
    ./a.out
    5
    6
    

    相关文章

      网友评论

          本文标题:(八)C++篇-main函数参数传递

          本文链接:https://www.haomeiwen.com/subject/npmcvrtx.html