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
.