WTL
WTL

Reputation: 113

Accepting Input from Command Line in C

How do I use scanf() IN C to accept multiple inputs from the command line? I'm trying to get a name, followed by an arbitrary number of values from a user, on the same line. I know the scanf() function is space/new line delimited.

For example the user enters: dog 2 5 1

I know scanf() will read the "dog", but how do I get it to read the following values. I can't use scanf("%s, %d, %d, %d", a, b, c, d) because there could be more than, or less than 3 values entered.

Upvotes: 0

Views: 505

Answers (2)

user5987642
user5987642

Reputation:

You could pass arguments to the main function itself. The prototype for main is

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

You could use this to read the command line arguments. argc gives the total number of arguments (separated by a space), and argv is a vector that holds it.

For example user will enter: ./yourExecutable dog 2 5 1 In this case the number of arguments would be 5 (including the name of your executable) and argv[0] would be your executable, argv[1] would be your "dog" and so on.

Upvotes: 1

xvan
xvan

Reputation: 4855

You can read the whole line to a string buffer using fgets().

Then split by spaces using strtok().

Upvotes: 0

Related Questions