10.13 — Command line arguments

The need for command line arguments

As you learned lesson 0.4 -- introduction to development, when you compile and link your program, the output is an executable file. When a program is run, execution starts at the top of the function called main(). Up to this point, we’ve declared main like this:

Notice that this version of main() takes no parameters. However, many programs need some kind of input to work with. For example, let’s say you were writing a program called Thumbnail that read in an image file, and then produced a thumbnail (a smaller version of the image). How would Thumbnail know which image to read and process? The user has to have some way of telling the program which file to open. To do this, you might take this approach:

However, there is a potential problem with this approach. Every time the program is run, the program will wait for the user to enter input. This may not be a problem if you’re manually running this program once from the command line. But it is problematic in other cases, such as when you want to run this program on many files, or have this program run by another program.

Let’s look into these cases further.

Consider the case where you want to create thumbnails for all the image files in a given directory. How would you do that? You could run this program as many times as there are images in the directory, typing out each filename by hand. However, if there were hundreds of images, this could take all day! A good solution here would be to write a program that loops through each filename in the directory, calling Thumbnail once for each file.

Now consider the case where you’re running a website, and you want to have your website create a Thumbnail every time a user uploads an image to your website. This program isn’t set up to accept input from the web, so how would the uploader enter a filename in this case? A good solution here would be to have your web server call Thumbnail automatically after upload.

In both of these cases, we really need a way for an external program to pass in the filename as input to our Thumbnail program when Thumbnail is launched, rather than having Thumbnail wait for the user to enter the filename after it has started.

Command line arguments are optional string arguments that are passed by the operating system to the program when it is launched. The program can then use them as input (or ignore them). Much like function parameters provide a way for a function to provide inputs to another function, command line arguments provide a way for people or programs to provide inputs to a program.

Passing command line arguments

Executable programs can be run on the command line by invoking them by name. For example, to run the executable file “WordCount” that is located in the root directory of the C: drive on a Windows machine, you could type:


In order to pass command line arguments to WordCount, we simply list the command line arguments after the executable name:

C:\>WordCount Myfile.txt

Now when WordCount is executed, Myfile.txt will be provided as a command line argument. A program can have multiple command line arguments, separated by spaces:

C:\>WordCount Myfile.txt Myotherfile.txt

This also works for other command line operating systems, such as Linux (although your prompt and directory structure will undoubtedly vary).

If you are running your program from an IDE, the IDE should provide a way to enter command line arguments.

In Microsoft Visual Studio, right click on your project in the solution explorer, then choose properties. Open the “Configuration Properties” tree element, and choose “Debugging”. In the right pane, there is a line called “Command Arguments”. You can enter your command line arguments there for testing, and they will be automatically passed to your program when you run it.

In Code::Blocks, choose “Project -> Set program’s arguments”.

Using command line arguments

Now that you know how to provide command line arguments to a program, the next step is to access them from within our C++ program. To do that, we use a different form of main() than we’ve seen before. This new form of main() takes two arguments (named argc and argv by convention) as follows:

You will sometimes also see it written as:

Even though these are treated identically, we prefer the first representation because it’s intuitively easier to understand.

argc is an integer parameter containing a count of the number of arguments passed to the program (think: argc = argument count). argc will always be at least 1, because the first argument is always the name of the program itself. Each command line argument the user provides will cause argc to increase by 1.

argv is where the actual argument values are stored (think: argv = argument values, though the proper name is “argument vectors”). Although the declaration of argv looks intimidating, argv is really just an array of C-style strings. The length of this array is argc.

Let’s write a short program named “MyArgs” to print the value of all the command line parameters:

Now, when we invoke this program (MyArgs) with the command line arguments “Myfile.txt” and “100”, the output will be as follows:

There are 3 arguments:
0 C:\MyArgs
1 Myfile.txt
2 100

Argument 0 is the path and name of the current program being run. Argument 1 and 2 in this case are the two command line parameters we passed in.

Dealing with numeric arguments

Command line arguments are always passed as strings, even if the value provided is numeric in nature. To use a command line argument as a number, you must convert it from a string to a number. Unfortunately, C++ makes this a little more difficult than it should be.

The C++ way to do this follows:

When run with input “567”, this program prints:

Got integer: 567

std::stringstream works much like std::cin. In this case, we’re initializing it with the value of argv[1], so that we can use operator>> to extract the value to an integer variable (the same as we would with std::cin).

We’ll talk more about std::stringstream in a future chapter.

The OS parses command line arguments first

When you type something at the command line (or run your program from the IDE), it is the operating system’s responsibility to translate and route that request as appropriate. This not only involves running the executable, it also involves parsing any arguments to determine how they should be handled and passed to the application.

Generally, operating systems have special rules about how special characters like double quotes and backslashes are handled.

For example:

MyArgs Hello world!


There are 3 arguments:
0 C:\MyArgs
1 Hello
2 world!

Typically, strings passed in double quotes are considered to be part of the same string:

MyArgs "Hello world!"


There are 2 arguments:
0 C:\MyArgs
1 Hello world!

If you want to include a literal double quote, you have to backslash the double quote:

MyArgs \"Hello world!\"


There are 3 arguments:
0 C:\MyArgs
1 "Hello
2 world!"


Command line arguments provide a great way for users or other programs to pass input data into a program at startup. Consider making any input data that a program requires at startup to operate a command line parameter. If the command line isn’t passed in, you can always detect that and ask the user for input. That way, your program can operate either way.

10.14 -- Ellipsis (and why to avoid them)
10.12 -- Recursion

151 comments to 10.13 — Command line arguments

  • J34NP3T3R

    hey guys sorry for the trouble
    but i forgot about this part std::stringstream and >>
    which chapter was this ?

    • J34NP3T3R

      never mind sorry. it was explained further that std::stringstream is from future lessons.
      i have the habit of asking questions before moving on because i wanted to understand each section before moving to the next.

  • Hi there,
    It just occurred to me why there is no main version of

    I just made a quick google search but could not understand the gist of stackoverflow related question that tried to explain.

    • Joshua

      There's a few reasons probably. One reason I can think of is that std::vector and std::string are not part of the C++ language itself, but are instead part of C++'s standard library. Different companies might have their own implementation of those types of containers, so forcing them to include the standard library implementation would be bad design.

  • Yousuf

    "when you compile and link your program, the the output is an executable file" --> This line repeats "the" two times.

  • Andreas Krug

    Two small code example fix suggestions:
    - Chapter "Using command line arguments"
    std::cout << count << ' ' << argv[count] << '\n'; instead of std::cout << count << " " << argv[count] << '\n';
    - Chapter "Dealing with numeric arguments"
    Rearrange the header files order from <iostream> <string> <sstream> <cstdlib> to <cstdlib> <iostream> <sstream> <string> as recommended in lesson 2.11 (Best practice: ..., with the headers in each section sorted alphabetically.)

  • Simone

    Do you have any easy to understand methods to read formal parameters in function declarations?
    For example `char *argv[]` confuses me a bit, is it an array of pointers to chars? A pointer to an array of type char?
    I generally understand assignments when they're done in a function but when passed through arguments I have a hard time remembering if there will be an implicit conversion, an array that decays etc.
    Thanks for the help!

    • Tony

      `char *argv` is just a C-style string. So `char *argv[]` is an array of C-style strings (as written in the tutorial).

      `char *argv[]` is the same as `char **argv` simply because the array that is passed as an argument decays into a pointer (so writing `int array[]` or `int *array` in the function parameter is the same thing).

      ^That is if I got it correctly.

  • SamiRA


    I have a couple of questions regarding this snippet:

    1) When we declare the parameter as char* argv[], we don't have to use the keyword 'const' but when I want to define that in the code below, it gives me a compile-time error that," can't convert from const char[6] to char*". Why is it OK as a parameter, but as a local variable it is not?


    2) I was wondering why the last three lines don't output the same as the first two lines?! Actually the last three lines, output the whole string 'Hello World' while in the first two lines in each iteration only one string separated by space is printed.

    • nascardriver

      1) "Hello" and "World" are string literals, they cannot be modified. By removing the `const`, you're saying that they can be modified, but that doesn't work. `argv`'s value doesn't come from string literals. The values it gets are allocated at run-time and can be modified.

      2) When you write 2 string literals next to each other they get concatenated. "Hello" "World" is the same as "HelloWorld".

  • aHMED

    >> As you learned lesson 0.4 -- introduction to development, when you compile and link your program, the compiler produces an executable file.

    "the compiler produces an executable file. " or "the LINKER produces an executable file."?

    >>Much like function parameters provide a way for a function to provide inputs to another function

    Isn't it better to rephrase, "provide a way for a function to provide inputs to a function". A function's parameters provide inputs for itself not other functions, right?

  • Amir

    I was understanding everything at beginning of tutorial till the previous lesson . I need advice please . should I start learning about files and data structure and comeback to this lesson or should I skip it and check it later when I get some knowledge about files and this all . I feel confuse really :(

  • Alek

    hey,I got a few questions:
    1:Executable programs can be run on the command line... this sentence and the rest of it I don't get what you mean, where can we write these codes to work? "C:\>WordCount"

    . I wonder why does it have to be a pointer to a pointer.any idea ?
    3:when we say for example :argv[1] doesn't this one refer to a single character ?then why when we use std::cout to print it we get a string ?

  • kavin

    Hi, in the last example line 20, we could use curly brackets to initialize like we did before right?

  • Ged

    1. Could you explain this a bit more?

    You said std::stringstream works like std::cin. But what happens exactly? Variable convert gets a value of "432" (example). And how does it turn to an integer? Or was this specifically made so we could change a string with numbers to an integer?

    • Ged

      And also. In one lesson you used std::exit(1), in this you used exit(1). Is exit(1) used by C and std::exit(1) used by C++?

      • nascardriver

        Yes. C++ moved all function from C into the `std` namespace. They're still accessible without `std::` by including the header with an extension, eg.

        The function might also be accessible without `std::` when you include the C++ header. That's not standard behavior, use `std::`.

    • nascardriver

      `std::stringstream` uses the same conversion methods as `std::cin` and `std::cout`. You can input data as a string and extract it as a number, just like you can enter a string on the command line and extract it as whatever type you want.

      • Ged

        Wrote a program to get a better understanding. I kinda understand what it does, but having a difficult time understanding the steps, like what specifically happens at the first line and the second line. So I wrote what I think happens.

        std::stringstream convert(numberString) is similar to? (std::cin >> convert = numberString); // Variable "convert" takes "45" and stops when it reaches "l";

        // convert = 45 // "45 has no data type till now?"

        convert >> numberInt // the value 45 is assigned to "numberInt" which converts it into data type "int"?

        • nascardriver

  • hellmet

    Similarly, if I wanted this output,

    The input would be

  • Hi need help,
    You gave the example of the program my Args. I want to know how do we invoke "Myfile.txt" and "100".

    • Open a console/terminal (OS-specific)
      Navigate to your executable (IDE-specific)
      Run your executable and pass arguments

      Your IDE probably has a way of passing arguments to your program so you don't have to run it manually, you'll have to google how to do it.

  • Muskan

    Are there any other parameter other than argc and argv which we can pass in main method???

  • cdecde57

    I am just wondering.

    This lesson seems to be harder than the others to me and I don't completely understand it. I understand argc and argv what I don't understand is the way it can receive it. How do I have a user send input that is created into an argument to open another file? or Like edit a directory full of files then how do I directly edit them after I received the input?

    Am I a little confused on the general idea of what goes down? Sorry if I don't make sense or am getting things wrong because I just need help on this lesson.

    • If you're using Windows, you can drag a file onto your program.exe and program.exe will be launched argv[1] set the file's path.
      If you're launching your program through a console/terminal, you can specify the paths by writing them after your program's name, as shown in this lesson.
      You shouldn't write to `argc` or `argv`, modifying them only affect the variables. File IO is covered in lesson 18.6 and 18.7. You should be able to understand them (at least enough to use file io) already.

      • cdecde57

        Thanks! That really makes more sense now.

        I will have to review file IO sometime and maybe more in-depth, other places as well so I can make like a database or something for a program. I think that would be cool.

        So, once I have the argument set (like someone dragged a file onto it) would I select argv[1] and then I can just edit it like a regular variable (depending becuase if it is like a text file then I would need to know file IO right?).

        Anyways, thanks!

  • Alireza

    Hello dear,
    You just mentioned how to pass arguments and take them from command line. But you didn't mention how to deal with taken arguments. For example: If user inputs two numeric arguments, how do we add them ? Or something like this.(e.g. rm command in linux which renames files. Or command line music player which takes file name and plays it)

    • Alex

      I'm not sure what you mean by "taken arguments". If the user inputs two numeric arguments and you want to add them, convert them to numbers as shown in the lesson, and then add them. I'm not sure I understand what you're getting at with the other examples.

  • masterOfNothing

    Sorry for this stupid question, but in case of the program with the output:

    0 C:\MyArgs
    1 Myfile.txt
    2 100

    Is MyArgs the location of a compiled .exe file from the project?

    I called mine from windows command line where debug .exe file is located, e.g., >"C:\Users\...\...\bin\Debug\learncpp.exe" Arg1.txt 100

    But the return code showed full path with .exe file extension at the end for the 0 (first) argument (which is the program file itself). You call it from the .exe file, right?

    • Alex

      Typically parameter 0 will be the location where the executable resides. Executables don't remember where they're compiled from.

      And yes, you can call executables directly from the .exe file. That's the whole point of them being executable. :)

  • X

    How is this conversion happening?

    If the conversion fails, then myint = 0. Cool. But there is no "else if" or another "if" to do the actual conversion in a non-fail case? So how is myint receiving the value from convert? Explain, please.

    • Alex

      First (convert >> myint) evaluates, which will try to do the extraction, and returns convert. Next, !convert is evaluated. This returns true if there was an error.

      Thus, myint = 0 only executes if the extraction caused an error.

  • hassan magaji

    hi Alex,
    in the first paragraph you wrote "up to this point we've _decleared_ main...
    shouldnt we've "defined" main...
    thanks by the way

  • Jon

    If you're passing let's say a TXT file as a command line argument, are there any restrictions to where the file must be located? Is the default path the same directory as the program? And if you want to use a file in a different location, do you just type in the entire path for it?


    • Hi Jon!

      Your program receives the path that you give it. It's up to you to figure out where the file is actually located.

      Compiled as "learncpp"

      Sample calls
      ./learncpp ../link.txt

      ./learncpp link.txt

      If your terminal/console has expansion capabilities, those will happen before your program runs.

      ./learncpp $(ls)

  • Kelvin

    How can I add a condition for the arguments? For example, the users can only input numerical integer.

    • The user can do what they want and you can't stop them, because the program isn't running at that time.
      You have the check if the provided arguments match what you expected. For example by checking the fail bit of an @std::stringstream or the idx argument passed to @std::atoi.

  • Adam

    I have seen code examples where they define the main function argument type but don't provide any parameters (from the OpenCV website):

    What is the purpose of this?


  • pete

    Hi alex,
    can you discuss (or point to..) how to extract data from other files as an input?

  • Ishak

    can you explain this piece of code, please? if argc is less than 1 this piece of code starts running, why? what are we trying to do ? "On some operating systems, argv[0] can end up as an empty string instead of the program's name. We'll conditionalize our response on whether argv[0] is empty or not" ? I don't understand what the means, and I don't understand whats the purpose of this code and how it works. I tried reading this multiple times.  Thanks for any help

      • Ishak

        Thank you nascardriver for the help. I have better understanding now. I have some follow up questions if you don't mind.

        - Should we use that piece of code to check for too few arguments in program "MyArgs" (the one before dealing with numeric arguments)?

        - Why can't we just do this argv[1] >> myint?

        - What exactly is a string-stream variable ?

        Thanks again for the help, and the amazing material.

        • 1. You should always check if there are enough elements (arguments) before accessing an array (argv).
          I wouldn't use the check provided here. I'd use preprocessor to determine the OS and shift the index that way. You don't need to worry about this too much, do what works on your OS and fix it once you want to port your code.

          2. argv[1] is a const char*. A const char* doesn't have an operator>>.

          3. It's like @std::cin and @std::cout but it doesn't print anything. You can use it to format strings and numbers and get the resulting string from it.

    • Petr

      This is confusing, because the condition

      is evaluated as true even when argc == 0! In that case,

      probably causes segmentation faul.

  • Anon

    Hey Alex,

    Why don't you just use the atoi function from the C standard library.

    Thanks so much for all your help.

    God bless!

  • Angmar

    Hello again, Alex.

    Would you recommend using std::stoi instead of stringstream in that particular case? stoi looks a bit simpler to me as a beginner.

    [code]#include <iostream>
    #include <string>
    using namespace std;

    main(int argc, char** argv)
      for (int i = 1; i < argc; i++) {
        cout << stoi(*(i + argv)) << endl;
      return 0;

  • Tal

    Is there way to check if the input is a float?
    I used

    But the conversion doesn't fail if the input is 10.9 for example.

    • Alex

      As you noticed, operator>> will extract whatever it can. So if you try to extract 10.9 to an int, it will extract the 10, and leave the .9 in the input stream.

      std::stringstream doesn't provide any way to determine if the value is a float. Of course, you could always just extract to a float value if that's a valid choice. Alternatively, you could read your input into a std::string and then look at the string to see if it has a decimal.

  • My dear c++ Teacher,
    Please accept my many thanks for you answered my question about main() arguments and for your suggestion to read here and post my question.
    First of all I use compilers online and I do not understand what is "command line".
    I run program

    by compiler
    and output was
    There are 1 arguments:
    0 /t
    I run by
    and output was
    There are 1 arguments:
    0 main
    With regards and friendship.

    • Alex

      Once you compile your program using, you can type "main myFile.txt 100" in the green box labeled "Default Term". This will run the program you compiled with the command line arguments you typed in.

      • My dear c++ Teacher,
        Please accept my many thanks for you answered my question and for your helpful answer. I typed that you suggest me and output is
        There are 3 arguments:
        0 main
        1 my file.txt
        2 100
        However I understand nothing but that have to learn every past lesson before learn present.
        With regards and friendship.

  • Hi, Alex my name is Ngabo, i am from in Africa
    I like so much your great tutorials.

    so, i have a question about this top <<command line arguments>>
    is it possible to give a pop up message at start up program like " # MyArgs please enter your argument? : myfile.txt"

    is my question clear ?

    • Alex

      Hello Ngabo from Africa, thanks for visiting the site!

      Once the program has started executing, it's too late to have the user pass in command line arguments. But you are free to have your program output anything or ask the user to input anything once it is running.

      Perhaps I missed the point of your question?

  • Rohit

    Hi Alex! Got some doubts.
    1) stringstream creates a variable convert, then how can we convert the initilized value to int using conver>>myint. I mean to say how this statement works? please explain.
    2) what is the diff b/w exit(0) and exit(1)? and is there anything exit(2) or exit(3) or......?

    • Alex

      1) stringstream works like std::cin does -- except instead of getting input from the user, you can give it input. Then you use operator<< to extract the output to a variable of your choice.
      2) exit returns an error code back to the OS. 0 means "everything went okay". A non-zero values means "something went wrong". In most cases, this error code is ignored, but it can be useful if you have another program calling your program and that other program needs to know whether your program succeeded or not.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]