Student4Life

Question: “How do I read in input from a C program” or “How do I read input from the command line in C” ??

Answer: Easily

Aside from the usual inclusion of stdio.h and stdin.h you just have to loop through the char* array in main.

#include <stdlib.h>

#include <stdio.h>

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

{

int i;

printf ("Number of arguments provided: %d\nThey are:\n", argc);

for(i=0;i<argc;i++) {

printf ("%s\n",argv[i]);

}

return 1;

}

The above snippet outputs the following:

./ProgramName MyArgument AnotherArgument

Number of arguments provided: 3

They are:

./ProgramName

MyArgument

AnotherArgument

With the traditional C main method, argc gets the number of arguments provided at the command line. Also, this example assumes the name of the program is “ProgramName” (in C the program name is always the first argument).