0

Let's say I have a program which tells you when you are going to die. I need the user's age for that. But the user can give me his age or birth day.

printf("Tell me your age or brith day\n");

if(scanf("%d", &age)!=1){
printf("error");

}
else if(scanf("%d %d %d", &day,&month,&year)!=3){
printf("error");

I tried it like this but it doesn't work. Only first if works, not the second one.

Again, basically, all I want is to give user 2 different options. 2 different ways to tell me his age.

Gardener
  • 2,591
  • 1
  • 13
  • 22

1 Answers1

4

I'd use fgets to get a line of input, then use sscanf to try each possibility:

#include <stdio.h>

int main(void)
{
    char buf[2048];
    int day, month, year, age;
    printf("Tell me your age or brith day\n");
    fflush(stdout);
    fgets(buf, sizeof buf, stdin);

    if (sscanf(buf, "%d %d %d", &day,&month,&year)==3)
    {
        printf("Your birthday is %d/%d/%d\n", day, month, year);
    }
    else if(sscanf(buf, "%d", &age)==1){
        printf("You are %d years old.\n", age);
    }
    else
        printf("error");

    return 0;
}
Fred Larson
  • 60,987
  • 18
  • 112
  • 174