How to stop fscanf when user hits Enter if <max args is entered
I have 3 char arrays, declared this way:
char arg1[25];
char arg2[25];
char arg3[25];
I prompt the user to enter some arguments this way:
fscanf(stdin, "%s %s %s", arg1, arg2, arg3);
printf(" %s %s %s", arg1, arg2, arg3);
My problem is that the user can only enter values ββfor arg1 and arg2 and then press Enter.
How can I use fscanf so that the user doesn't have to type all 3 arguments before hitting Enter?
The values ββin these arrays must be used with execvp.
Thank.
+3
source to share
1 answer
fgets
will accept input until Enter. sscanf
can then parse the input into whitespace-separated strings and return the number of rows checked.
#include <stdio.h>
int main(){
char input[100] = "";
char arg1[25] = "";
char arg2[25] = "";
char arg3[25] = "";
int scanned = 0;
fgets ( input, sizeof input, stdin);
scanned = sscanf ( input, "%24s%24s%24s", arg1, arg2, arg3);
if ( scanned == 1) {
printf ( "%s\n", arg1);
}
if ( scanned == 2) {
printf ( "%s %s\n", arg1, arg2);
}
if ( scanned == 3) {
printf ( "%s %s %s\n", arg1, arg2, arg3);
}
return 0;
}
+5
source to share