Please forgive me for asking this simple question, but I only started C recently with the original C book by Kernigham and Ritchie, using Notepad++ (as VSCode just throws errors when I try to compile anything and I don't know yet how to overcome that), and using gcc from the command line.
Anyway, the question I have is, how do I read a number from a command line argument?
For example, myProgram 2
I know that the main()
definition is as shown below, and that argc
is a counter, and argv
is a pointer to a character array (I think this is right) containing the command lines.
int main(int argc, char *argv[]){
return 0;
}
The question I have is, how do I convert the character 2
(which is my command line argument, it could be any number) to an int
?
I've googled and a few things come across casting, which I believe is changing one data type to another, and I have tried:
int a = (int)(argv[1]);
which compiles, but with a warning saying "cast from pointer to integer of different size". It compiles, but then won't run.
I suspect the answer I need is simple, it's just beyond my knowledge at the moment.