I'm trying to write a program that reads various user inputs. These string inputs can contain or not whitespace. I made a version that works good, but needs a while loop (inside clearStdin function) as show below:
#include <stdio.h> #include <stdlib.h> void clearStdin(void); int main(void) { char name1[8], name2[5]; printf("Write a name: "); fgets(name1, sizeof name1, stdin); clearStdin(); printf("Write another name: "); fgets(name2, sizeof name2, stdin); clearStdin(); printf("First name is: %s\n", name1); printf("Second name is: %s\n", name2); return 0; } void clearStdin(void){ int c; while(( c = getchar() ) != '\n' && ( c != EOF )); } I tried to use
scanf("%7[^\n]", name1); scanf("%*[^\n]"); scanf("%*c"); and also other ways. My question is: There is other ways for the program to work without using the while (or another) loop? Any scanf or fgets way only?
Exemple input:
Write a name: RafaelBluhm Write another name: Tainah Julião Required output:
First name is: RafaelB Second name is: Tain Fails outputs (Other ways):
First name is:Tain Second name is:@�
char c;atclearStdin(): should beint c;scanf("%8[^\n]", name1);should bescanf("%7[^\n]", name1);stderrfor a prompt:fputs("Write a name: ", stderr)orfprintf(stderr, "Write a name: ");