Thread: Scanf problem

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    1
    Rep Power
    0

    Scanf problem


    Hi All,

    I've compiled a program that does some math and asks the user if they want to do another calculation at the end (the users response sets the true/false condition (Y or y for True and any other key for false) for the while statement.

    The scanf that reads the users selection is not working, when I have it set to %c for ASCII it just skips that step and ends the program. If I have it set to %d it stops and prompts the user to enter the value, however when a value is entered it goes into a runaway loop.

    Not sure if the problem lies with the scanf or somewhere else, any help appreciated.

    #include <stdio.h>
    #include <stdlib.h>

    int main (void)
    {
    //constants definition
    const float MOW_SPEED = 2;

    //variables definition
    float length, width;
    float mowingArea, mowingTime;
    char select = 89;

    while(select == 89 || select ==121)
    {
    printf("Please enter a length between 10m and 30m: ");
    scanf("%f", &length);
    if(length > 10 && length < 30)
    {
    printf("Please enter a width between 5m and 20m: ");
    scanf("%f", &width);
    if(width > 5 && width < 20)
    {
    mowingArea = length * width;
    mowingTime = mowingArea/MOW_SPEED;
    printf("The time needed is: %.1f\n", mowingTime);
    printf("\nPress Y and enter to do another calculation or any other key and enter to exit.\n\n");
    scanf("%c",&select);
    }
    else
    {
    printf("Error: Width out of range\n");
    }
    }
    else
    printf("Error: Length out of range\n");
    }
    system("pause");
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,413
    Rep Power
    1871
    This just answered in another thread

    Take time to check out the use of [code][/code] tags as well.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo