I made a program to see what your name is, if you were a male or female, how old you are, and if I should call you as Mrs, Ms, Mr, or just by your full name depending on the previous conditions. When I pick my gender as female and enter a first name, last name, and a age that's over or equal to 20 I ask if that person is married, however for whatever reason the program skips over the getchar, and just finishes the program.
Here is the code:
#include <stdio.h>
#include <string.h>
int main()
{
char gender;
char fName[15];
char lName[15];
char mar;
char str[] = "Then I shall call you";
int age = 0;
printf("What is your gender (M or F): ");
gender = getchar();
printf("First name: ");
scanf("%s", fName);
//fgets(fName, 16, stdin);
//fName[strcspn(fName, "\n")] = 0;
printf("Last name: ");
scanf("%s", lName);
//fgets(lName, 16, stdin);
//lName[strcspn(lName, "\n")] = 0;
printf("Age: ");
scanf("%d", &age);
puts("");
if(gender == 'F' || gender == 'f')
{
if(age >= 20)
{
printf("Are you married, %s (y or n)?: ", fName);
//scanf("%c", &mar);
mar=getchar();
printf("%c\n", mar);
if(mar == 'Y' || mar == 'y')
printf("%s Mrs. %s.\n", str, lName);
else if(mar == 'n' && age >= 20|| mar == 'N' && age >= 20)
printf("%s Ms. %s.\n", str, lName);
}
else
printf("%s %s %s.\n", str, fName, lName);
}
else if(gender == 'M' || gender == 'm')
{
if(age >= 20)
printf("%s Mr. %s.\n", str, lName);
else
printf("%s %s %s.\n", str, fName,lName);
}
return 0;
}
And the output:
What is your gender (M or F): F
First name: Jane
Last name: Doe
Age: 25
Are you married, Jane (y or n)?:
I also have another question as to when I used fgets instead of scanf to read the string. As I heard to typically stay away from scanf when reading strings I tried fgets but the output wasn't as I wanted it to be.
Here is the output when I used fgets instead of scanf:
What is your gender (M or F): M
First name: Last name: Joe
Age: 23
Then I shall call you Mr. Joe.
The output should be as it was when I used the scanf so that The last name is underneath the first name.
getchar()with multi-char input inscanforfgets. When you press Enter, that produces a character as well, which you have to handle.scanf(" %c", &mar);orgetchar(); mar=getchar(). The problem is because of the newline character left over by the previous scanf.scanf(), 1) always check the returned value (not the parameter value) to assure the operation was successful. 2) when using a input/format string that does not automatically skip over white space, insert a space into the format string before the (for instance) %s, so any leading white space is automatically consumed. 3) when using the format%salways use the max length modifier (which needs to be 1 less than the actual input buffer length) I.E.%14sfor a 15 char input buffer.