If your main.c looks like this:
int main() {
// Here is the code.
}
cannot accept the argument from the command line, because that signature (int main()) does not expect to receive arguments from the operating system.
should look like this:
int main(int argc, char *argv[]) { ... }
Read the second word you type in the terminal (argv[1])
You must use the variable argv[1]
Also, you must put in an initial check to make sure the user actually supplied the argument
argv[0] is always the name of the program (or path) that is running
- argv[0] is for the program
- argc (parameter the counter) is always at least 1 (because argv[0] always exists)
- argv[1] onwards are for user data
For example, if you want to enter an “int” as arguments
- Capture the text string using argv[1]
- Convert that string to an integer using a special C function
You need to use the atoi (ASCII to Integer) function from the from the <stdib.h> library
Capture the argument “3” from the command line
const char *var1 = argv[1];
CONVERSION: Use atoi() to convert the string (“3”) to an integer (3)
int var2 = atoi(var1);
example:
code of “a.c”:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
const char *var1 = argv[1];
int var2 = atoi(var1);
printf("%d\n", var2);
}
compiles a.c and creates the executable a (with gcc)
gcc a.c -o a
execute a with argument 123
./a 123
You should see 123 in the console/terminal.
