ACH
ACH

Reputation: 369

Why does my program skip to completion if a float is entered first, but works with integers?

The problem I occurs when I input any float as the first number. Everything else just goes to completion, but the output looks like a stored memory address perhaps?
If I use any integer the program works properly. I would like for the program to convert any numerical input from the user into integers.
While I explicitly ask for an integer input, if the user inputs 2.2 I would like the program to call it 2, and then move onto asking for their second input.

#include <stdio.h>

int main(void)
{
    // creating two variables
    int firstNumber;
    int secondNumber;

    //asking user to input a number
    printf("Enter your first integer value: ");
    scanf("%d", &firstNumber);
    printf("\nThe integer value you entered is %d.\n", firstNumber);

    //asking user to enter another number
    printf("\nEnter your second integer value: ");
    scanf("%d", &secondNumber);
    printf("\nThe second integer value you entered is %d.\n", secondNumber);

    /* system("pause"); */
    return 0;
}

Upvotes: 2

Views: 254

Answers (1)

Stephen Docy
Stephen Docy

Reputation: 4788

Because the first scanf() successfully reads the whole number part of the float as an integer and then the second scanf() tries to read another integer but fails because it runs into the decimal point. The thing to realize is that scanf() for an integer will stop reading when it hits an non-numerical character, and that it will leave that character in the input stream.

Upvotes: 5

Related Questions