Start New Discussion within our Software Development Community

I have seen C++ programs that allow you to type a string (in the case I saw it was a file name) after the name of the program, but in the same command (before pressing enter) when you go to run the program and the program parsed it as it would an input handeled later in the program using cin. Can someone tell me how to do that?

In C/C++, command-line arguments (AKA shell arguments) are passed through optional parameters to the main() function. These parameters, by convention named argc and argv, are an integer count of the arguments passed to it, and a pointer to an array of char arrays, which hold the string values of the arguments themselves. Under most (but for some reason, not all) systems, argv[0] is the name of the program itself.

For example, you can write a program that echoes its arguments simply by looping on argc:

#include <iostream>

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++)
    {
        std::cout << argv[i] << std::endl;
    }
    return 0;
}

The downside to using shell arguments is that there is no checking for the type or number of arguments passed; thus, you need to check argc to make sure that it is a legitimate number of arguments, then parse the arguments for their values.

This question has already been answered. Start a new discussion instead.