CPP 036 – main function & command-line arguments

Şimdi kadar main fonksiyonumuzu int main() şeklinde gördük ama aslında bir alternatif kullanımı da var:

int main(int argc, char *argv[]){

}

Yani iki tane argüman alıyor. Bunlardan biricisi aldığı parametre sayısını, ikincisi ise bir parametreleri string olarak tutan bir array

argc
An integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1.

argv
An array of null-terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1], and argv[argc] is always NULL.

Nasıl kullanacağız?

#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {

	for (int i{}; i < argc; i++) {
		cout << argv[i] << endl;
	}

	return 0;
}

Kodu yazdıktan sonra .exe nin bulunduğu klasöre gidip cmd üzerinden programı parametre verip çalıştırabilirsiniz:


https://learn.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-170


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *