Question

In C programming language i need to do this question:

-Write down a program to enter a number. The program reads in the number and determines if it is even or odd. If the number is even, the program requests the user to enter his age. If the age is 18 or above, the program outputs the message “You can vote!” else the message “You cannot vote”. If the number is odd, the program requests the user to enter a character. If the character is lowercase the program displays the message “Good Luck!” else the program outputs the message “Work hard!”.

Unfortunately. when i enter an odd number say 3, it displays "enter a character: Good luck!" before i have a chance to input the character.. It goes directly to the last else. Help please!

int main()
{
int num,age;
char c;
printf("Enter number: ");
scanf("%d", &num);

if (num%2 == 0)
    {
     printf("Age: ");
     scanf("%d",&age);

        if (age>=18)
            printf("You can vote!");
        else
            printf("You cannot vote.");
    }
 else
 {
  printf("Enter a character: ");
  scanf("&c",&c);

        if(c>='A' && c<='Z')
            printf("Work hard!");
        else
            printf("Good luck!");
  }

}
Was it helpful?

Solution 2

The trailing enter from the previous scanf is taken up as input for the next scanf

You need to "eat up" the trailing newline:

with something like this :

while( (c=getchar()) != '\n' && c!= EOF);

or simply use :

scanf(" %c", &c); //Notice a space

Also fix :

scanf("&c",&c); to scanf("%c",&c);

OTHER TIPS

In line :

scanf("&c",&c);

It should be ("%c", &c); but even if You fix this, it will still be wrong, because scanf leaves '\n' character in input buffer, so next time, when you read a character with scanf("%c", &c) it will assing c='\n'. You can fix this easily by changing to this

 scanf(" %c", &c);

Notice ' ' before %c. This empty space tells scanf to eat all trailing white spaces(including \n) before reading any character from input.

That's common problem with scanf used for reading mixed data and characters, so keep it always in mind.

From what I noticed your main has no return. put return 0; at the end of function main.

You have a type in your last scanf() format spec. Because of that, scanf() does nothing (returning 0 as number of conversions). You should always check the result of scanf().

In place of this (I presume &c is just a typo):

scanf("&c",&c);

Try this:

scanf("%c%*c", &c);

The %c specifier only consumes one character, leaving a newline in the stdin buffer; that gets read by the next call and fails if(c>='A' && c<='Z').

%*c tells it to read another character and discard (*) it, which should get rid of the newline.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top