1

I am doing a lab for an intro programming class

I have to make sure that an integer is entered. I thought this would do it but when I put in a letter it repeats in an endless loop.

I found this solution in another post

int num;
char term;

if (scanf("%d%c", &num, &term) != 2 || term != '\n')
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

But im not sure what I did wrong. Why is it not working in my code?

#include <stdio.h>

int main(void)
{
    int oneVar;
    char term;
    double numOne;
    double numTwo;
    double sum;
    double dif;
    double quo;
    double mult;
    int checker = 1;

    do
    {
        printf("Please choose one of the following:\n""1) Add\n""2) Subtract\n""3) Divide\n""4) Multiply\n""5) Quit\n");

        if (scanf("%d%c" , &oneVar ,&term) != 2 || term != '\n')
        {
            printf ("This is not valid input\n\n");
            checker = 1;
        }
        else if (oneVar == 5)
        { 
            printf("Thank you. Goodbye.\n");
            checker = 0;
        }   
        else if (oneVar != 1 && oneVar !=2 && oneVar != 3 && oneVar != 4)
        {
            printf("This is not a valid input\n\n");
            checker = 1;
        }
        else
        {
            printf("Please enter the first number:\n");   
            if (scanf("%lf%c" , &numOne ,&term) != 2 || term != '\n')
            {
                printf ("This is not valid input\n\n");
                checker = 1;
            }
            printf("Please enter the second number:\n");
            if (scanf("%lf%c" , &numTwo ,&term) != 2 || term != '\n')
            {
                printf ("This is not valid input\n\n");
                checker = 1;
            }
            else if (oneVar == 1)
            {
                sum = numOne + numTwo;
                printf("The sum is: %.2lf\n" ,sum);
                checker = 0;
            }    
            else if (oneVar == 2) 
            {
                dif = numOne - numTwo;
                printf("The difference is: %.2lf\n" ,dif);
                checker = 0;
            }
            else if (oneVar == 3) 
            {
                quo = numOne / numTwo;
                printf("The quotient is: %.2lf\n" ,quo);
                checker = 0;
            }
            else if (oneVar == 4) 
            {
                mult = numOne * numTwo;
                printf("The product is: %.2lf\n" ,mult);
                checker = 0;
            }
            else if (oneVar == 5)
            {
                printf("Thank you. Goodbye.\n");
                checker = 0;
            }
        }
    } while (checker == 1); 

    return(0);
}

My prof posted this Im not sure how it helps but I thought it might help someone To make sure that a user-input number is an integer you can use the notion of casting. Casting is a way to tell C to treat a variable as if it were a variable of a different type.

so, if I have something like this:

double myDouble;

myDouble = 5.43;

printf ("%d", (int) myDouble);

It will tell C to print myDouble, but to treat it like an integer. Only the 5 will be printed and you won't get any type mismatch errors. You can use casting to check to see if an input number is an integer by comparing the input to the (int) cast of the number. Something like this should work:

if(inputNum == (int) inputNum)

You'll still get 1.0 and 2.0 passing as valid numbers, but that is ok for now.

harpun
  • 4,022
  • 1
  • 36
  • 40
  • 7
    Here's something to add to your education: Learn to think like a programmer. Saying "it goes haywire" tells us absolutely nothing about what exactly happens. Not only does figuring out and articulating the result you get make it much easier for people on stackoverflow to help you, but it also helps you developer your analytical skills. – Jonathan Wood Oct 25 '13 at 18:47
  • Are you on unix or MS Windows? On MS Windows it doesn't quite work like that – Vorsprung Oct 25 '13 at 19:05
  • I said that because I wasnt sure how to describe it but basically it just repeats over and over in an endless loop. I am using a raspberry pi with a custom OS for my program. Like I said I am a beginner sorry if my language isnt up to par but Im doing my best! hopefully that clarifies my question. – Samantha Christine Oct 25 '13 at 19:24
  • Hey Samantha, welcome to StackOverflow! You might find [the question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist) helpful here - it'll help us better answer your question and give you the help you need. Good luck and happy programming! – Christian Ternus Oct 25 '13 at 19:30
  • If you found that solution on StackOverflow, I would expect it to be down voted. – Clifford Oct 25 '13 at 20:30
  • I note from your other posts that you are having a few issues with compilation and accurate syntax - mostly typos that yield diagnostic messages confusing to a beginner, but which get closed down quickly on StackOverflow. If you are coding with a basic text editor and command line compilation on RPi, I can recommend [Code::Blocks for RPi](http://store.raspberrypi.com/projects/codeblocks), the syntax highlighting editor and integrated debugger will help you find your own solutions to these starter issues. Its available via the Pi Store or by `sudo apt-get install codeblocks`. – Clifford Oct 25 '13 at 20:55
  • Thanks Clifford I will check that out! – Samantha Christine Oct 25 '13 at 20:57
  • possible duplicate of [Check if input is integer type in C](http://stackoverflow.com/questions/4072190/check-if-input-is-integer-type-in-c) – Igor Ševo Oct 26 '13 at 16:19

2 Answers2

1

Using the %c to "consume" the end of line is not a good solution. If the user enters say:

123 abc<newline>

num will be 123, but term will be the space character. If you enter a letter rather than a number, the scan will stop without consuming any of the characters, the next input call will return due to the already buffered line, and may still consume nothing. Your program loops continuously because every input statement is failing to consume the newline and returns immediately. The standard input functions wait for a complete line before returning, if the line is not read completely, input functions do not need to wait.

There are a number of solutions, many of which such as the one you used are flawed, the method below, forces the input buffer to be flushed up to and including the newline.

int check = scanf( "%d", &num ) ;
while( getchar() != '\n' )
{
   // do nothing
}

if( check != 2 )
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

If you use the %c format specifier at the end of the input, then a slightly different flush is necessary since the character input may be a newline:

int check = scanf( "%c", &ch ) ;
while( ch != '\n' && getchar() != '\n' )
{
   // do nothing
}
Clifford
  • 88,407
  • 13
  • 85
  • 165
1

Why complicate things?

char x = 0;
scanf("%c", &x);
if (x >= 0x41 && x <= 0x7A)
printf("you entered a letter");

In ASCII table, letters have values between 0x41 ("A") and 0x7A ("z"). So, you just need to check the ASCII value of the input. :)

Eutherpy
  • 4,471
  • 7
  • 40
  • 64
  • 1
    She said she is in an intro to programming course so without explanation, this is not an answer. – Stephen Melvin Oct 25 '13 at 20:04
  • This is a much simpler way of doing it so I changed it to use this logic instead but it still doesn't work when I enter a letter for the second input so the first number to go in the equation. Where it says "Please enter the first number" what I want it to do is print "This is not valid input\n" and then start at the beginning so return to the initial menu. but this is the output I get :Please choose one of the following: 1) Add 2) Subtract 3) Divide 4) Multiply 5) Quit 1 Please enter the first number: e Please enter the second number: The sum is: -36046567177420279509914 with more numbers – Samantha Christine Oct 25 '13 at 20:37
  • Basically it doesnt allow you to put anymore input. – Samantha Christine Oct 25 '13 at 20:39
  • Just saw the prof posted not to worry about letters so I will just submit it as is because everything else works. She also posted this not sure if it helps someone else. – Samantha Christine Oct 25 '13 at 20:48