Skip to content

Instantly share code, notes, and snippets.

@csknk
Last active March 15, 2020 12:02
Show Gist options
  • Save csknk/196e25b0486cb93e39120b03a423f74f to your computer and use it in GitHub Desktop.
Save csknk/196e25b0486cb93e39120b03a423f74f to your computer and use it in GitHub Desktop.
Simple integer input in C, using `fgets()` to get the entire line as a string and `strtol()` to parse the integer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* end = NULL;
char buf[255];
long n = 0;
printf("Enter an integer:\n");
while (fgets(buf, sizeof(buf), stdin)) {
n = strtol(buf, &end, 10);
if (end == buf || *end !='\n') {
printf("Not recognised as an integer. Please enter an integer:\n");
} else break;
}
printf("You entered %ld\n", n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment