Thread: Need help formating scanf, please.

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    2

    Need help formating scanf, please.

    I'm new to C-programming.

    Here's what I'd like to do:

    The user inputs T47.2 Scanf recognizes T as a char and 47.2 as a floating point number.

    This code doesn't work:
    Code:
    #include <stdio.h>
    int main() {
    char letter;
    float number;
    while(1) {
    printf("Letter and Number: ");
    scanf("%c%f", &letter, &number);
    }
    return 0;
    }
    I put the printf and scanf functions in an infinite loop so I can test various inputs.

    It compiled successfully using c99, and here's what I get after three inputs:

    >./a.out
    Letter and Number: T47.2
    Letter and Number: J73.8
    Letter and Number: Letter and Number: I99.1

    Something isn't working as I intend for it. It's as if "J" and "73.8" are treated as two separate inputs.

    I'd greatly appreciate any input as to how I might fix my scanf format to function properly.

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    %c does not skip \n left by %f in the input stream
    add space after %f to skip whitespaces
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    2
    Thanks, vart

    I changed the statement to:
    Code:
    scanf("%c%f%*c", &letter, &number);
    This accounts for the return character, while not assigning it.

  4. #4
    Registered User
    Join Date
    Feb 2010
    Posts
    15
    You can use the following code
    Code:
    #include <stdio.h>
    int main() {
    char letter;
    float number;
    while(1) {
    printf("Letter and Number: ");
    scanf("%c %f", &letter, &number);
    getchar();
    }
    return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  3. scanf and formating data
    By xddxogm3 in forum C Programming
    Replies: 23
    Last Post: 04-16-2004, 03:50 PM
  4. scanf issue
    By fkheng in forum C Programming
    Replies: 6
    Last Post: 06-20-2003, 07:28 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM