[prev] 48 [next]

Application: Input Using scanf()

Standard I/O function scanf() requires the address of a variable as argument
  • scanf() uses a format string like printf()
  • use %d to read an integer value

    #include <stdio.h>
    …
    int answer;
    printf("Enter your answer: ");
    scanf("%d", &answer);
    

  • use %f to read a floating point value   (%lf for double)

    float e;
    printf("Enter e: ");
    scanf("%f", &e);
    

  • scanf() returns a value — the number of items read
    • use this value to determine if scanf() successfully read a number
      • scanf() could fail e.g. if the user enters letters