Reputation: 55
So, I'm trying to do this code that says "Hello Mr" or "Hello Mrs" depending on the sex of the user, but when I run the program, it doesn't let me type my name, but why?
Also, I tried to use fgets() but the compiler says " too few arguments to function 'fgets' "
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void flushstdin()
{
int c;
while((c=getchar())!= '\n' && c != EOF);
}
int main () {
float sex;
char name[60];
printf("\nInform your sex: 1 if you are male, 2 if you are female.");
while(scanf("%f",&sex)!=1 || sex!=1 && sex!=2){ //In case the person typed something different of 1,2.
printf("\nInform a correct value, 1 or 2.\n");
flushstdin();
}if(sex==1){
printf("Inform your name.\n");
gets(name);
printf("\nHello Mr. %s \n",name);
}
if(sex==2){
printf("Inform your name.\n");
gets(name);
printf("\nHello Mrs. %s \n",name);
}
system("pause");
return 1;
}
Upvotes: 1
Views: 68
Reputation: 853
In this case, when pressing enter to pass the data of whether the user is female or male, the character for enter which is '\n' is still on queue within the input buffer. This occurs when using scanf. This means that the gets() function that follows will read the '\n' character that is still in the buffer without asking the user first.
A simple solution would be adding two lines of code after asking the user's gender that will receive the remaining input(s) in the buffer:
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void flushstdin() {
int c;
while((c=getchar())!= '\n' && c != EOF);
}
int main () {
float sex;
char name[60];
printf("\nInform your sex: 1 if you are male, 2 if you are female.");
while(scanf("%f",&sex)!=1 || sex!=1 && sex!=2){ //In case the person typed something different of 1,2.
printf("\nInform a correct value, 1 or 2.\n");
flushstdin();
}
//new code, extracts input from buffer until it reads a '\n' character or buffer is empty
char c;
while(( c = getchar()) != '\n' && c != EOF);
//end of new code
if(sex==1){
printf("Inform your name.\n");
gets(name);
printf("\nHello Mr. %s \n",name);
}
if(sex==2){
printf("Inform your name.\n");
gets(name);
printf("\nHello Mrs. %s \n",name);
}
system("pause");
return 1;
}
Upvotes: 2