4

Possible Duplicate:
Simple C scanf does not work?

Why does scanf("%c", &letter); not working. the rest is working

#include <stdio.h>

main(){
    int number;
    float number1;
    char letter;
    char letter2 [5];

    printf("Enter an int: ");
    scanf("%d", &number);
    printf("Enter a float: ");
    scanf("%f", &number1);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("Enter a string: ");
    scanf("%s", letter2);

    printf("INT = %d\n", number);
    printf("FLOAT = %f\n", number1);
    printf("LETTER = %c\n", letter);
    printf("LETTER2= %s\n", letter2);

    getch();
}
Community
  • 1
  • 1
sample
  • 43
  • 1
  • 4

2 Answers2

4

This is because the newline (return key) after feeding float is counted as a character.

This is not a bug but it is due to fact that "\n" is considered a character in C and if you have to ignore it, you need to do that manually.

The simplest solution for your case is to eat up the newline as follows:

scanf("%f", &number1);
getchar();

This Link will help.

Community
  • 1
  • 1
sud03r
  • 19,109
  • 16
  • 77
  • 96
  • @sample: No, please see the link provided by Paul in the comment, your question is a duplicate of the other question. – Bobby Dec 06 '10 at 12:54
  • @sample c is most robust language thats why it is use for device drivers.How you can say that c having problem. – Ishu Dec 06 '10 at 12:56
3

scanf reads the whitespace that is left in the buffer from the previous line. To skip the whitespace, add a space to the scanf:

scanf(" %c", &letter);

The space means "skip whitespace" and the the %c means "read the following character.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220