Skip to Content
✨ v2.2.4 Released - See the release notes
DocumentationMCA-418 LAB on C++ ProgrammingQ13: Demonstrate Command Line Arguments in C++

Q13. Demonstrate Command Line Arguments

Question:
Write a program to demonstrate command line arguments.


My Approach

C++ me command line arguments ka use program ko inputs directly terminal se dene ke liye hota hai, bina program ke andar cin use kiye.
Ye arguments main(int argc, char* argv[]) ke through pass hote hain:

  • argc → total arguments ki count (program name + extra inputs).
  • argv → array of C-strings jo arguments ko hold karta hai.

Real-life scenario:
Agar mujhe ek file manager ya cybersecurity script banana ho, to mujhe har baar manually input lene ki jagah command line se arguments pass karne hote hain.


Program Code

File Name: command_line_args.cpp

#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << "Total Arguments: " << argc << endl; cout << "Program Name: " << argv[0] << endl; if (argc > 1) { cout << "Arguments Passed:" << endl; for (int i = 1; i < argc; i++) { cout << "Arg " << i << ": " << argv[i] << endl; } } else { cout << "No extra arguments provided!" << endl; } return 0; }

How to Run

  1. Compile the program:
g++ command_line_args.cpp -o args_demo
  1. Run without arguments:
./args_demo

Output:

Total Arguments: 1 Program Name: ./args_demo No extra arguments provided!
  1. Run with arguments:
./args_demo Intesab MCA-418 NMU

Output:

Total Arguments: 4 Program Name: ./args_demo Arguments Passed: Arg 1: Intesab Arg 2: MCA-418 Arg 3: NMU

Explanation

  1. argc count karta hai total arguments ka.
    • Agar input ./args_demo Intesab diya, to argc = 2.
  2. argv[0] → hamesha program ka naam hota hai.
  3. argv[1] … argv[n] → jo bhi arguments hum dete hain wo yaha store hote hain.

Real-Life Scenario

  • Linux commands jaise cp file1 file2 → yaha cp program hai aur file1, file2 arguments hain.
  • Cybersecurity me hum nmap 192.168.1.1 run karte hain to nmap program hai aur IP address argument hai.
  • Isi tarah agar mai apna project Sortify (file manager) ya Talkum (chat app) me run karu to mai kuch configurations command line se pass kar sakta hoon.

Conclusion

  • Command line arguments se program ko flexible banaya ja sakta hai.
  • Ye feature especially useful hai jab automation, scripting, ya user input without interaction ki requirement hoti hai.

Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live 

Last updated on