0

uni year 2 student learning c++, and i have this code i created, within this code i use cin to ask for user input but my instructor want "You need to use argc and agrv[] in your main function. So users can inputs information into your program when they run it. For instance, "yourprogram.exe -P 50"." but i dont know how i could implement it. Thank the help

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

    if (userchouise == "P" | userchouise == "A" )
    {

        if (userchouise == "P") //        {
            cin>>uservlue;
            if (uservalue >= 100 | uservalue <= 0)
            {

                cout << "p " << endl;// Invalid duty cycle value
                return 0;
            }
            else
            {
               cout<<uservalue<<endl;


            }
            return 0;
        }
        if (userchouise == "A") //  can only input values from 0-7
        {
            int userPort;
            cout << "enter port number between 0 to 7" << endl;
            cin >> userPort;
            if (userPort >= 0 | userPort <= 7)
            {



            }
            else
            {
                cout << "a " << endl;//Invalid ADC channel number
            }
            return 0;
        }

    }
    else
    {
        cout << "I " << endl;
    }
    return(0); 
}
Zhen Tang
  • 1
  • 1
  • 1
    `argv` is an array of char *, `argv[0]` is the program, `argc` is the number of elements in the array. If "yourprogram.exe -P 50" `argc` is 3, `argv[0]` is "yourprogram.exe" , `argv[1]` is "-P" and `argv[2]` is "50" – bruno Apr 23 '20 at 07:39
  • Please read about [mcve]. Most of your code is not related to your question and could be removed. Actually it shuold be removed because it calls functions whose declaration you didnt post, so others cannot compile it. – 463035818_is_not_an_ai Apr 23 '20 at 07:40

2 Answers2

2

The argc/argv is the C-way of passing command-line parameters to the program, which is still used in C++, but use std::vector<std::string> args(argv+1, argv+argc); as first statement to work with the parameters as a vector of strings or use a library which can make it more convenient to work with parameters the way it is expected and to provide a help message (What parameter parser libraries are there for C++?).

Remark, the argv+1 is used because by convention, the fist parameter is the name of the program.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
0

This will print out all the command line arguments. Modify the code to do whatever you want

    for(int i = 0; i < argc; i++)
        std::cout << "argument " << i << ": " << argv[i] << std::endl;