Thread: Particulars of the scanf function

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    9

    Question Particulars of the scanf function

    Consider the following code:

    #include <stdio.h>

    int main() {
    float x;
    int i;
    char c;

    printf("type three inputs:\n");
    scanf("%3d %5f %c", &i, &x, &c);
    printf("i is %d, x is %f and c is %c", i, x, c);
    return 0;
    }

    input: 454 3567.7 s

    which prints to the screen:

    i is 454, x is 3567.000000, c is 7


    My question is exactly how does the computer interpret this input?

    I think it is something like the following:

    %3d => first 3 characters are taken in as i, i.e. 454

    %5f => the next 5 characters are taken as x, i.e. 3567. (Note: I have included the decimal)

    %c => takes the next character only as c, i.e. 7

    s is disregarded

    My theory also is that spaces do not affect the input

    i.e. if I were to input: 454 3567.7 s

    the same output would result, however, if I were to input the following:

    input: 45 4 3567.7 s

    no output would result as 45 4 cannot be successfully converted by %3f

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by bthomson900 View Post
    My theory also is that spaces do not affect the input

    i.e. if I were to input: 454 3567.7 s

    the same output would result, however, if I were to input the following:

    input: 45 4 3567.7 s

    no output would result as 45 4 cannot be successfully converted by %3f
    Try it! I get output when I use 45 4 3567.7 s as input. Check out this site for some good scanf (and general C references): The C Library Reference Guide.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  4. Replies: 5
    Last Post: 02-08-2003, 07:42 PM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM

Tags for this Thread