What happens if the user inputs a value that is not a number?

QuestionsQuestions8 SkillsProPython Control StructuresSep, 05 2025
0109

If the user inputs a value that is not a number, the program will typically encounter an error when trying to process that input as an integer. To handle such cases, you can implement input validation. Here's an example in C that checks if the input is a valid integer:

#include <stdio.h>

int main() {
    int number;
    char term;

    while (1) {
        printf("Enter a positive number (0 or negative to exit): ");
        if (scanf("%d%c", &number, &term) != 2 || term != '\n') {
            printf("Invalid input. Please enter a valid integer.\n");
            // Clear the input buffer
            while (getchar() != '\n');
            continue;
        }

        if (number <= 0) {
            break; // Exit the loop if the number is 0 or negative
        }

        printf("You entered: %d\n", number);
    }

    return 0;
}

In this code:

  • We use scanf to read the input and check if it successfully reads an integer followed by a newline character.
  • If the input is invalid, we print an error message and clear the input buffer to allow for new input.

0 Comments

no data
Be the first to share your comment!