user47835
user47835

Reputation: 159

accepting user inputs from the standard input where the amount of variable inputs could vary

I want to accept variables from the standard input but I dont want to define how many variables I am accepting so that the user could submit two or three variables.

for example I would have:

char key;
char name1[100];
char name2[100];


printf("Hello! insert your command:\n");
scanf("%c %s %s",&key, name1, name2);

but the user isnt required to insert a second name so that inputs "F John" and "L John Doe" "X" would all be accepted. Basically I don't want the input length to be predetermined I only need it to accept up 1 2 or 3 variables. Is scanf the proper way to do this or is there a better method?

currently it waits for all 3 variables to be assigned

Upvotes: 0

Views: 215

Answers (2)

DYZ
DYZ

Reputation: 57033

You can use fgets() to read the whole input string and then sscanf() from the string into the variables. sscanf() returns the number of successfully read fields. You can use this number to decide which variables have been initialized.

char buffer[100];
int n;
printf("Hello! insert your command:\n");
fgets(buffer, sizeof(buffer), stdin);
n = sscanf(buffer, "%c %s %s", &key, name1, name2);
# 1, 2 or 3

As it has been noted in a comment, the rest of the line will be read, too (up to 100-1=99 characters). I assume that there are no more fields of interest in the rest of the line.

Upvotes: 1

autistic
autistic

Reputation: 15642

Is scanf the proper way to do this or is there a better method?

Yes, scanf is entirely appropriate for this. However, you need to be aware that the spaces you've used in your format string aren't; they have a different meaning, as they match not just one single space but any sequence zero or more whitespace characters (including spaces, tabs, newlines). You'll want to use a %*1[^ ] directive, instead. You could define this as #define SPACE_FORMAT "%*1[^ ]" for clarity, and use it as follows:

int n = scanf("%c" SPACE_FORMAT "%s" SPACE_FORMAT "%s", &key, name1, name2);

Note carefully how I've stored the return value into n; if scanf successfully matches and assigns to:

  • only the first object (pointed to by &key), it'll only return 1...
  • the first (pointed to by &key) and second (pointed to by name1) object, it'll return 2...
  • ... and so forth. If scanf fails due to some read error or reaching EOF, it'll return EOF (which is a negative integer), instead.

Upvotes: 1

Related Questions