User Tools

Site Tools


en:cs:cpp:common:commandlinearg

Command Line Arguments

In C++ we know that all programs must have 1 entry point. This is usually the main function.

When the program runs, it starts executing code from the beginning of the input function. If we want, we can also take the arguments given to the program when binding it.

int main(int argc, char* argv[])
  • The argc int parameter holds the number of arguments to the program. It always has at least 1 value. Because the first argument is always the program itself.
  • argv is an array of char pointers. Each element points to a C-style array. The length of this array is argc.

Below you can see the program that prints its arguments on the screen.

#include <iostream>
 
int main(int argc, char* argv[])
{
    std::cout << argc << " adet arguman var.\n";
 
    // Her bir bağımsız değişkeni döngüye sokun ve sayısını ve değerini yazdırın
    for (int count{ 0 }; count < argc; ++count)
    {
        std::cout << count << ' ' << argv[count] << '\n';
    }
 
    return 0;
}

Command line arguments are always taken as strings. Therefore, even if the argument is a numeric value, it is taken as a string. If we want to get a numeric value, we need to take it as a string and then convert it.

#include <iostream>
#include <sstream> // std::stringstream
#include <string>
 
int main(int argc, char* argv[])
{
	if (argc <= 1)
	{
		// On some operating systems, argv[0] may result in an empty string instead of the name of the program.
		// We will condition our response on whether argv[0] is empty or not.
		if (argv[0])
			std::cout << "Usage: " << argv[0] << " <number>" << '\n';
		else
			std::cout << "Usage: <program name> <number>" << '\n';
 
		return 1;
	}
 
	std::stringstream convert{ argv[1] }; // Set a stringstream variable called convert initialized with the entry in argv[1]
 
	int myint{};
	if (!(convert >> myint)) // do the conversion
		myint = 0; // if the conversion fails, set myint to a default value
 
	std::cout << "Integer: " << myint << '\n';
 
	return 0;
}

When you type something on the command line (or run your program from the IDE), it is the responsibility of the operating system to translate and route this request appropriately. This includes not only executing the executable, but also parsing the arguments to determine how they are handled and passed to the application.

UCH Viki'den alınmıştır. https://wiki.ulascemh.com/doku.php?id=en:cs:cpp:common:commandlinearg

en/cs/cpp/common/commandlinearg.txt · Last modified: 2025/05/02 22:26 by ulascemh