简体   繁体   中英

C++ - accepting command line arguments?

So this was my original code:

#include <iostream>

using namespace std;

int main ()
{
    float x;  
    cout << "Please enter an integer value: ";
    cin >> x;

    if ((x >= 100) && (x < 200)) {
        cout << "split";
    } else if (x == 0 ||x == 1 ) {
        cout << "steal";
    } else {
        cout << "split";
    } 

    system("pause");
}

It works perfectly, but I need it to run this way:

C:\> program.exe 109

it will read 109 and give the output - "steal" .

C:\> program.exe 0.5

it will read 0.5 and give me the output "split" .

What do I have to add to my original code to do this?

Change your main to

int main (int argc, char** argv)

The you can check number of specified parameters to your program in argc and the values (as char * ) in argv . You can convert that values to float using std::stof

float x = 0.0f;
if (argc > 1) {
    x = std::stof(argv[1]);
} else {
    std::cerr << "Not enough arguments\n";
    return 1;
}

Please note that the first argument to the program is the name of the executable itself ( program.exe in your case), so you need to check for at least two arguments.

References: http://en.cppreference.com/w/cpp/string/basic_string/stof

you can do this by using command line arguments. Here is format for main function:

int main (int argc, _TCHAR* argv[])
{
}

Here argc represents number of arguments(returns 2 in your case, program.exe 0.5 )

argv represents two strings. 1st containing program.exe and second containing 0.5 .

This way you can solve you problem

Can we have more clarity on the question? Do you want to know how to execute the code using command line arguments? In that case here it is:

int main (int no_of_args, char* arglist[])
{
}

In argList , the first item holds the name of the executable and subsequent items hold the inputs provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM