Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔵 Core C++  ·  Lesson 35

Command Line Arguments in C++

In this lesson: Pass arguments to a C++ program with argc and argv — run from terminal with examples. In Hindi & English.

What are command line arguments?

Most beginner programs ask for input with cin after they start. Command line arguments are a different way to give input: you type the values after the program's name when you *launch* it.

Terminal
./result Aman 78 85 91

Here Aman, 78, 85 and 91 are handed to the program before it starts running. Real tools work this way — g++ main.cpp -o main passes three arguments to the compiler. Arguments are ideal for file names, options and scripts that run without a human typing input.

The main() signature

To receive arguments, write main with two parameters:

C++
int main(int argc, char* argv[])
// or, equivalently:
int main(int argc, char** argv)
ParameterMeaning
argcArgument count — how many strings were passed, *including* the program name
argvArgument vector — array of C-strings; argv[0] is the program name
argv[argc]Always a null pointer (end marker)

For ./result Aman 78 85 91: argc is 5, argv[0] is "./result", argv[1] is "Aman", … argv[4] is "91".

Example 1: print every argument

C++
#include <iostream>

int main(int argc, char* argv[]) {
    std::cout << "argc = " << argc << "\n";
    for (int i = 0; i < argc; i++) {
        std::cout << "argv[" << i << "] = " << argv[i] << "\n";
    }
    return 0;
}
Terminal
g++ args.cpp -o args
./args hello "Class 12" 2026
argc = 4 argv[0] = ./args argv[1] = hello argv[2] = Class 12 argv[3] = 2026

Quotes group words with spaces into a single argument: "Class 12" is one argument.

Example 2: numbers from arguments

Arguments are always text. Convert them with std::stoi (int) or std::stod (double), and check the count first.

C++
#include <iostream>
#include <string>
#include <stdexcept>

int main(int argc, char* argv[]) {
    if (argc < 3) {
        std::cerr << "Usage: " << argv[0] << " <name> <mark1> [mark2 ...]\n";
        return 1;
    }

    std::string name = argv[1];
    int total = 0;
    try {
        for (int i = 2; i < argc; i++) {
            std::size_t used = 0;
            int mark = std::stoi(argv[i], &used);
            if (argv[i][used] != '\0')                  // "7x" is not a valid mark
                throw std::invalid_argument(argv[i]);
            total += mark;
        }
    } catch (const std::exception& e) {
        std::cerr << "All marks must be whole numbers.\n";
        return 1;
    }

    int subjects = argc - 2;
    std::cout << name << ": total " << total
              << ", average " << static_cast<double>(total) / subjects << "\n";
    return 0;
}
Terminal
./result Aman 78 85 91
Aman: total 254, average 84.6667

The program returns 1 on bad input — a non-zero exit code tells scripts that something went wrong.

Copying arguments into a vector

Working with raw char* is awkward. Copy them into modern types once:

C++
#include <string>
#include <vector>

int main(int argc, char* argv[]) {
    std::vector<std::string> args(argv + 1, argv + argc);   // skip program name
    for (const auto& a : args) {
        if (a == "--help") { /* show help */ }
    }
    return 0;
}

Now you can compare with ==, use .size() and pass the vector to functions.

Passing arguments from an IDE

ToolWhere to set arguments
Terminal / Command Promptprogram.exe arg1 arg2 or ./program arg1 arg2
Code::BlocksProject → Set programs' arguments
Dev-C++Execute → Parameters
Visual StudioProject Properties → Debugging → Command Arguments
VS Code"args": ["arg1", "arg2"] in launch.json

Where command line arguments are used

  • Passing a file name: ./marks-report students.csv
  • Options and flags: --verbose, -o output.txt
  • Automation: batch scripts and scheduled jobs that run without user input
  • Competitive and practical exams sometimes read test sizes this way

Common mistakes

  • Using argv[1] without checking argc — crashes when no argument is given.
  • Forgetting that argv[0] is the program name, so real arguments start at index 1.
  • Comparing C-strings with == (argv[1] == "--help" compares pointers). Use std::string(argv[1]) == "--help" or strcmp.
  • Treating arguments as numbers without converting them.
  • Calling std::stoi without handling the exception for non-numeric text — and forgetting that stoi("7x") silently returns 7 unless you check how many characters were used.
🏋️ Practice

Write a program calc that takes three arguments — a number, an operator (+ - x /) and another number — and prints the result, e.g. ./calc 12 x 5 prints 60. Print a usage message when the argument count is wrong and handle division by zero. (Use x for multiply because * is expanded by most shells.)

Summary

  • Command line arguments are values typed after the program name when it is launched.
  • Receive them with int main(int argc, char* argv[]).
  • argc counts arguments including the program name; argv[0] is the name.
  • Arguments are strings — convert with stoi/stod and handle errors.
  • Always check argc before reading argv[i].

Related: functions, strings, file handling, exception handling.

Frequently Asked Questions

What are argc and argv in C++?
argc (argument count) is the number of command-line arguments, including the program name. argv (argument vector) is an array of C-strings: argv[0] is the program name, argv[1] the first real argument, and so on up to argv[argc - 1]; argv[argc] is a null pointer.
How do I convert a command line argument to an integer in C++?
Arguments always arrive as text. Use std::stoi(argv[1]) for int, std::stod for double, or std::stol for long (from <string>). Wrap the call in try/catch because stoi throws std::invalid_argument if the text is not a number.
How do I pass command line arguments in Code::Blocks or VS Code?
In Code::Blocks use Project → Set programs' arguments. In Visual Studio open Project Properties → Debugging → Command Arguments. In VS Code, add an "args" array to launch.json, or simply run the compiled program from the terminal: ./program arg1 arg2.
Is argc ever zero?
On normal systems argc is at least 1 because argv[0] holds the program name. The C++ standard technically allows argc to be 0, so robust programs check argc before using argv[0].
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicFile Handling in C++ Your progress: 35 / 81 (43%) · Lesson 36 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free