Thread: C help

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    18

    C help

    I have a code:

    printf ("Enter first number: ");
    while (scanf("%lf",&first)!=1){
    printf ("%s is not a number\n",first); ??????????????
    while (getchar()!='\n');
    printf ("Enter first number again: ");
    If a user type for example ABC how can i printf that message

    example:

    "ABC is not a number"
    Last edited by kzzmzz; 02-02-2017 at 07:34 AM.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Read the input into a buffer with fgets(), and parse the buffer with sscanf(). If sscanf() fails, print the buffer.

    Also, be sure to use code tags when posting code.

  3. #3
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    Is there anyway to do this with scanf? Im new to C language and didnt use fgets and sscanf yet, thats way im trying to do this with scanf.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Sure. If scanf() fails to read a double, follow up with a string read and print the result.

    Be aware that using scanf() to read strings has some potential difficulties (e.g. stops reading at whitespace by default) and dangers (does not automatically limit the number of characters read which could potentially lead to a buffer overrun, though there are ways of preventing this).

    Try it yourself, and if you want advice on how to improve it, post the updated code.

  5. #5
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    Sorry, but do you mean with %s specifier if so i tryed that and got message
    (null) is not a number
    I have read that scanf has many potential problems but im trying to learn scanf first and after that i will try with fgets,sscanf ...

    Sorry, my english is not so good

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Yes, %s is used to read a string. Post the code (in code tags) that is causing that error if you want help fixing it.

  7. #7
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    This is my code:

    Code:
    double first;
    
    printf ("Enter first number: ");
    while (scanf("%lf",&first)!=1){
    printf ("%s is not a number\n",first);          ??????????????
    while (getchar()!='\n');
    printf ("Enter first number again: ");
    and im getting "null is not a number" message

  8. #8
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You should post a complete (simplified) program that compiles and exhibits the problem.

    On line 4, when scanf() fails to read a double (with bad input), the offending input is still sitting in the input buffer. You need to do a subsequent read to get that input, and it has to be stored in the correct data type (e.g. char array).

    Attempting to print a double using %s is both invalid, and wrong anyway (since the value of "first" is not changed on bad input).

    Code:
    print prompt
    while (read double with scanf) does not return 1
        read string with scanf
        print string and error message

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    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.

  10. #10
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    Ok, im reading a book " C primer plus 5-th edition by Stephan Prata" and im trying to resolve excersize 8 in Chapter 8

    In C Programming Language: Write A Program That Sh... | Chegg.com


    This is what i heve so far

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    char get_first(void);
    char get_choice (void);
    
    int main (void)
    {
        int choice;
        double first,second;
    
    
        while ((choice=get_choice())!='q')
        {
            switch(choice)
            {
            case 'a':     printf ("Enter first number: ");
                            while (scanf("%lf",&first)!=1)
                            {
                            printf ("%s is not a number\n",first);
                            while (getchar()!='\n');
                            printf ("Enter first number again: ");
                           }
                        printf ("\nEnter second number: ");
                        scanf ("%lf",&second);
    
                        break;
    
            case 's':
                        break;
    
            case 'm':
                        break;
    
            case 'd':
                        break;
    
            default:    printf ("Program error!\n");
                        break;
            }
        }
        return 0;
    }
    char get_choice(void)
    {
    
    int ch;
    
        printf ("Enter the operation of your choice:\n");
        printf ("a. add s. subtract\n");
        printf ("m. multiply d. divide\n");
        printf ("q. quit\n");
        ch=get_first();
        while (ch!='a' && ch!='s' && ch!='m' && ch!='d' && ch!='q')
        {
            printf ("Please respond with a, s, m, d or q.\n");
            ch=get_first();
        }
        return (ch);
    }
    
    char get_first(void)
    {
        int ch;
    
    
        ch=getchar();
        if (isupper(ch))                        
        {
            ch=tolower(ch);
        }
        while (getchar()!='\n')
        {
            continue;
        }
        return ch;
    
    }

    I have to do something like this:

    "Enter the first number: 22.4

    Enter the second number: one
    one is not a number.

    Please enter a number such as 2.5 or 3: 1

    22.4 + 1 = 23.4
    Enter the operation of your choice:
    and then question again

    "

    I want to try to write the code first in switch and after that to try to put that code in prototype function.


    I know how buffer works i think, when scanf read "ABC" for double var first he put that to buffer again and thats why i put
    Code:
    while (getchar()!='\n');
    but i need to read that from buffer before i clean it.

  11. #11
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    Quote Originally Posted by Matticus View Post
    You should post a complete (simplified) program that compiles and exhibits the problem.

    On line 4, when scanf() fails to read a double (with bad input), the offending input is still sitting in the input buffer. You need to do a subsequent read to get that input, and it has to be stored in the correct data type (e.g. char array).

    Attempting to print a double using %s is both invalid, and wrong anyway (since the value of "first" is not changed on bad input).

    Code:
    print prompt
    while (read double with scanf) does not return 1
        read string with scanf
        print string and error message

    I post but i need moderator to aprove that, i try your solution and it works fine now, this is what i did...

    Code:
    double first;
    char test[255];
    
    printf ("Enter first number: ");
    while (scanf("%lf",&first)!=1){
      scanf ("%s", test);                         //to pick input from buffer
    printf ("%s is not a number\n",test);
    while (getchar()!='\n');                      // clean buffer
    printf ("Enter first number again: ");

  12. #12
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    I hope im not bodering you, thank you for help.

    I have another problem in my code, when i hit for example "a" and then type two numbers i got result ok but when i got to manu again and hit another letter for example "s" nothing happend thats because i think '\n' is in buffer and how can i clean buffer before second main menu?

    I will later put all cases in a prototype function but i need to first solve problems,

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    char get_first(void);
    char get_choice (void);
    
    int main (void)
    {
        int choice;
        double first,second,result;
        char test[255];
    
        while ((choice=get_choice())!='q')
        {
            switch(choice)
            {
            case 'a':   printf ("Enter first number: ");
                        while (scanf("%lf",&first)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        printf ("\nEnter second number: ");
                        while (scanf("%lf",&second)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        result=first+second;
                        printf ("%.2lf + %.2lf = %.2lf\n",first,second,result);
                        break;
    
            case 's':   printf ("Enter first number: ");
                        while (scanf("%lf",&first)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
    
    
                        printf ("\nEnter second number: ");
                        while (scanf("%lf",&second)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        result=first-second;
                        printf ("%.2lf - %.2lf = %.2lf\n",first,second,result);
                        break;
    
            case 'm':   printf ("Enter first number: ");
                        while (scanf("%lf",&first)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        printf ("\nEnter second number: ");
                        while (scanf("%lf",&second)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        result=first*second;
                        printf ("%.2lf * %.2lf = %.2lf\n",first,second,result);
                        break;
    
            case 'd':   printf ("Enter first number: ");
                        while (scanf("%lf",&first)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        printf ("\nEnter second number: ");
                        while (scanf("%lf",&second)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        result=first/second;
                        printf ("%.2lf / %.2lf = %.2lf\n",first,second,result);
                        break;
    
            default:    printf ("Program error!\n");
                        break;
            }
        }
        printf ("Bye.");
        return 0;
    }
    char get_choice(void)
    {
    
    int ch;
    
        printf ("Enter the operation of your choice:\n");
        printf ("a. add s. subtract\n");
        printf ("m. multiply d. divide\n");
        printf ("q. quit\n");
        ch=get_first();
        while (ch!='a' && ch!='s' && ch!='m' && ch!='d' && ch!='q')
        {
            printf ("Please respond with a, s, m, d or q.\n");
            ch=get_first();
        }
        return (ch);
    }
    
    char get_first(void)
    {
        int ch;
    
        ch=getchar();
        if (isupper(ch))                        
        {
            ch=tolower(ch);
        }
        while (getchar()!='\n')
        {
            continue;
        }
        return ch;
    }

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    You need this
    while (getchar()!='\n');
    after your successful scanf calls 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.

  14. #14
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    The newline is likely left over from the previous scanf() calls. The second time through, "get_first()" will read in that newline before it enters the while() loop, and return that first newline after another one is read (which is an invalid menu command).

    If you want a quick solution, get rid of the while() loop in "get_first()", and change ch=getchar() to scanf(" %c", &ch) (and the type of "ch" to char). This will also read in a single character, but the space before the %c will eat up all the whitespace before attempting the read.

    Quote Originally Posted by kzzmzz View Post
    I will later put all cases in a prototype function but i need to first solve problems,
    You misunderstand the point of functions. They should be used to aid in development by separating out common functionality, not as a hasty afterthought.

  15. #15
    Registered User
    Join Date
    Feb 2017
    Posts
    18
    I did it I added code on line 6 and 7 to get rid of whitespace...


    Code:
    char get_first(void)
    {
        int ch;
    
        ch=getchar();
        if (isspace(ch))
            ch=getchar();
        if (isupper(ch))                        
        {
            ch=tolower(ch);
        }
        while (getchar()!='\n')
        {
            continue;
        }
        return ch;
    }
    about prototype function i was thinking to put this code in prototype becase its same in all cases, is it wrong to put this in prototype function?

    Code:
    printf ("Enter first number: ");
                        while (scanf("%lf",&first)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
                        printf ("\nEnter second number: ");
                        while (scanf("%lf",&second)!=1)
                            {
                                scanf("%s",test);
                                printf ("%s is not a number\n",test);
                                printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
                                while (getchar()!='\n');
                            }
    Last edited by kzzmzz; 02-03-2017 at 02:50 AM.

Popular pages Recent additions subscribe to a feed

Tags for this Thread