I am a C beginner trying to understand some nuances of scanf. This seems really trivial but I am struggling with reading inputs from stdin in "the correct way".
When terminal input is like string1 string3 string3
and I hit return, It works correctly and gives 3 in the result.
But when I give input like string1
and I hit return, I want the program to return 1 in the result
variable and break the loop. Which doesn't happen. The program just expects me to enter more input into the terminal.
#include <stdio.h>
#define nameBufferLen 20
int main () {
int result;
char name[nameBufferLen];
char opens[nameBufferLen];
char closes[nameBufferLen];
while(1) {
result = fscanf(stdin,"%s %s %[^\n]s", name, opens, closes);
printf("%s|%s|%s| AND Result len is : %d\n", name, opens, closes, result);
if (result!=3) {
break;
}
}
return 0;
}
I am curious to know what could be the approach and regex that enables me to do this with scanf
.
Here is the implementation that @Barmar mentioned:
#include <stdio.h>
#define nameBufferLen 19
#define str(s) str2(s)
#define str2(s) #s
int main (void) {
for(;;) {
char s[3 * (nameBufferLen + 1)];
if(!fgets(s, sizeof(s), stdin)) {
printf("err\n");
return 1;
}
char name[nameBufferLen+1] = { 0 };
char opens[nameBufferLen+1] = { 0 };
char closes[nameBufferLen+1] = { 0 };
int result = sscanf(s,
"%" str(nameBufferLen) "s"
"%" str(nameBufferLen) "s"
"%" str(nameBufferLen) "s",
name, opens, closes
);
if(result == 1)
break;
}
}
and example run:
a b c
a b
a
If you enter strings longer than 19 the excess will spill into the next variable. You can detect that with strlen()
of each of the variables. Alternatively you can parse the string s
with, for example, strpbrk()
.