Thread: About scanf

  1. #1
    Registered User
    Join Date
    Sep 2012
    Location
    Macau
    Posts
    7

    Lightbulb About scanf

    This is a BMI Calculator..That's no problem when using correctly.(Typing correct number)
    But, if I'm a bad guy and typing some letters…It would show “Don't trick me, Again(in Meters):” repeatedly but wouldn't let me typing anything(Like just skip "scanf")
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    
    int main(void)
    {
        float height = 0, weight = 0, BMI = 0;
        int OK = 0;
        printf("Welcome to BMI calculator.\nPlease type your height first(in Meters):");
        while(!OK){
            OK = scanf("%f", &height);
            if(height >0 && OK){
                printf("\nWell, not so tall :)\nAnd..Your Weight(in Kilograms):");
                OK = scanf("%f", &weight);
                while(weight <= 0 || !OK) {
                    printf("\nAgain(in Kilograms):");
                    OK = scanf("%f", &weight);
                }
            } else {
                printf("\nDon't trick me, Again(in Meters):");
                OK = scanf("%f", &height);   //be skipped?
            }
            if(!height || !weight) OK = 0;
        }
        BMI = weight / (height * height);
        printf("\nOk..your BMI is: %.2f\n", BMI);
        system("pause");
        return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What does scanf return?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Sep 2012
    Posts
    11
    scanf referencescanf - C++ Reference

  4. #4
    Registered User
    Join Date
    Sep 2012
    Location
    Macau
    Posts
    7
    Quote Originally Posted by laserlight View Post
    what does scanf return?
    zero..
    EVEN haven't print any msg at first time it step in else{}!
    Last edited by PlusA2T; 09-23-2012 at 10:26 AM.

  5. #5
    Registered User
    Join Date
    Sep 2012
    Posts
    11
    your program should write user's input into a string and then if it is correct convert it to a number and then calculate bmi.
    wait, i am working on it.

  6. #6
    Registered User
    Join Date
    Sep 2012
    Location
    Macau
    Posts
    7
    But why do the complier don't run my script?

  7. #7
    Registered User
    Join Date
    Sep 2012
    Posts
    11
    because the scanf function can not handle a string if you told it that you would enter a floating value.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by PlusA2T
    zero..
    EVEN haven't print any msg at first time it step in else!
    If scanf does return zero, then control would go to your else body. The thing is, scanf can also return EOF. The correct way to check is:
    Code:
    if (scanf("%f", &height) == 1 && height > 0 ){
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Sep 2012
    Location
    Macau
    Posts
    7
    Quote Originally Posted by laserlight View Post
    If scanf does return zero, then control would go to your else body. The thing is, scanf can also return EOF. The correct way to check is:
    Code:
    if (scanf("%f", &height) == 1 && height > 0 ){
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    
    int main(void)
    {
        float height = 0, weight = 0, BMI = 0;
        int OK = 0;
    printf("Welcome to BMI calculator.\nPlease type your height first(in Meters):");
        while(!OK){
            if (scanf("%f", &height) == 1 && height > 0 ){
    printf("\nWell, not so tall :)\nAnd..Your Weight(in Kilograms):");
                while(weight <= 0 && scanf("%f", &weight) < 1) {
    printf("\nAgain(in Kilograms):");
                    OK = scanf("%f", &weight);
                }
            } else {
    printf("\nDon't trick me, Again(in Meters):");
                scanf("%f", &height);
            }
            OK = (height || weight) ? 1 : 0;
        }
        BMI = weight / (height * height);
    printf("\nOk..your BMI is: %.2f\n", BMI);
    return0;
    }

    Same problem here..It seems that two lines haven't be executed at first time too..
    About scanf-2012-09-24-01-43-49-png
    Last edited by PlusA2T; 09-23-2012 at 11:46 AM.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > if (scanf("%f", &height) == 1
    But if you type in say "hello" then the next time around the loop and you do

    if (scanf("%f", &height) == 1
    the "hello" will STILL be there, and scanf will fail for exactly the same reason.

    You need some way (see the FAQ) of removing some garbage input, and restoring the input stream to some consistent state.

    Oh, and when posting code, make sure you "paste as text", so that your code looks like it is in post #1.
    Fancy HTML pastes screw the board formatting, resulting in a mess.
    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.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by PlusA2T
    Same problem here..It seems that two lines haven't be executed at first time too..
    The problem now is that when input fails, the input is left in the input buffer. You should be removing that input before trying again, e.g.,
    Code:
    } else {
        int c;
        printf("\nDon't trick me, Again(in Meters):");
        while ((c = getchar()) != '\n');
    }
    Notice that I removed the scanf call here because you will do that call in the next iteration of the while loop. Also, you should get rid of this:
    Code:
    OK = (height || weight) ? 1 : 0;
    because it is only OK if you have read both height and weight.

    When you read the weight, you should follow the same pattern. At the moment, you are comparing the weight before having read it.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Sep 2012
    Location
    Macau
    Posts
    7
    Not so understand that..
    Do it means scanf() is hard to do this? and where can I found lots of reference of C(like PHP: php.net)? (Not C++ or C#)
    Only let user input float and if not then yell user and let user input again.
    Can give a example code how to do that?
    Thanks!

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by PlusA2T
    Do it means scanf() is hard to do this?
    Nope, it just means you need to do a little more work to handle input errors and retry correctly if you want to use scanf. An alternative is to read the input as a string using say, fgets, then parse the string with sscanf. This way, you don't need to discard incorrect input because you have already read it as a string.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Sep 2012
    Location
    Macau
    Posts
    7
    Quote Originally Posted by laserlight View Post
    Nope, it just means you need to do a little more work to handle input errors and retry correctly if you want to use scanf. An alternative is to read the input as a string using say, fgets, then parse the string with sscanf. This way, you don't need to discard incorrect input because you have already read it as a string.
    Still no so understand...Why do the function "getchar()" make it works! It means I have to catch the "\n" myself? (But seems that scanf will ignore?)
    Lastly, My code here:
    Code:
    //
    //  BMIC.c
    //  BMIC
    //
    //  Created by PlusA2T on 12/9/23.
    //
    
    #include<stdio.h>
    #include<stdlib.h>
    
    int main(void)
    {
        float height = 0, weight = 0, BMI = 0;
        int OK = 0;
        printf("Welcome to BMI calculator.\nPlease type your height first(in Meters):");
        while(!OK){
            while (scanf("%f", &height) != 1 || height <= 0){
                if (height <= 0) printf("\nDon't trick me, Again(in Meters):");
                while(getchar()!='\n') continue;
            }
            printf("\nWell, not so tall :)\nAnd..Your Weight(in Kilograms):");
            while(scanf("%f", &weight) != 1 || weight <= 0) {
                printf("\nAgain(in Kilograms):");
                while(getchar() != '\n') continue;
            }
      OK = (height && weight) ? 1 : 0;
        }
        BMI = weight / (height * height);
        printf("\nOk..your BMI is: %.2f\n", BMI);
        return 0;
    }

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by PlusA2T
    Why do the function "getchar()" make it works! It means I have to catch the "\n" myself? (But seems that scanf will ignore?)
    The idea is to discard the invalid input by reading and ignoring the input until and including the newline character.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with while's and scanf's...
    By m600 in forum C Programming
    Replies: 14
    Last Post: 01-19-2010, 03:31 PM
  2. scanf
    By Ciaran789 in forum C Programming
    Replies: 4
    Last Post: 11-22-2009, 07:40 AM
  3. First scanf() skips next scanf() !
    By grahampatten in forum C Programming
    Replies: 5
    Last Post: 08-17-2004, 02:47 AM
  4. scanf
    By kurz7 in forum C Programming
    Replies: 2
    Last Post: 04-08-2003, 06:14 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

Tags for this Thread