Last active
March 15, 2020 12:02
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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