When I first started programming, i used to think that the only way to get any input from a user in a console application was to have them input it at the top of the program, before the rest of the code gets executed, and ask the user for more input if needed later during runtime. I would see programs that could be executed from a command line with values following the name of the executable. Something kinda like this:
I used to think that was done with magic, and was something only the most elite programmers could accomplish. But one day by the act of googleing, i found how this magic was achieved, and that it was in fact not magic at all. The trick is in how you declare main() in console applications. Normally, you would declare main() as:
The reason main() needs to be changed, is because as you should hopefully know, all console-based applications start execution at main(), which can be referred to for the duration of this post as the console entry point. When a console app is started, the OS automatically goes to the entry point to look for its first instruction. The only way to pass parameters into the console app BEFORE the os reaches the entry point, is with a slight change to main(), which enables you to pass variables into the entry point. Here is that change:
Thats all the magic there is. When main() is declared like that, ANY program you write using it will have the ability to have values passed from a command line. Like this:
Dont worry about the pointer ( * ). You won’t work that particular pointer directly in your program save once, usually. The best thing to do, in my opinion anyways to make manipulating the passed-in values easy, is to copy the entire argv array into another array, but instead of a char type array we use an string type array:
Now, you can use myArray to process and manipulate your passed in values.
NOTE: When you want to access a value stored in myArray, note that arrays start at 0, not 1. So using myArray will not get you the first parameter passed into main, but rather the 2nd value. KEEP THAT IN MIND!
The reason we copy argv to myArray is to make it easier on ourselves later, when we want to manipulate or process the values directly. Working with chars, especially char pointers, is a pain in the ass in my opinion and should be avoided where possible. The std::string object class in c++ provides user friendly functions by default to ease the manipulation of data stored in a string, and can be done relatively simpler then with chars. But thats just me, you can try to use char if you want, its up to you. But strings are safer and easier and rec
ommended 9/10 times.
🙂 Hope it helped.