how to make sure input is integer c
To make sure the input is an integer in C, you can use the scanf
function to read the input and check if it returns 1. Here's an example:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
if (scanf("%d", &num) != 1) {
printf("Invalid input. Please enter an integer.\n");
return 1;
}
printf("You entered: %d\n", num);
return 0;
}
This code prompts the user to enter an integer, reads the input using scanf
, and checks if the return value is 1. If the return value is not 1, it means that the input was not a valid integer. In that case, it prints an error message and returns 1. Otherwise, it continues with the rest of the code.