Anyone happen to know why this is? Thanks, Ash
Code:
/* Anytime you want to use input validation, always make the char array 2 bigger than what you need or it won't work.I'm
not sure why this is because it seems like the program below would work, but it you don't change str[6] to str[7], it
doesn't.
When fgets gets a string it will save 1 spot for the \0, and you'll need a space for the \n as well.
That's why in the program below which wants a 5 digit number, it seems like using "char str[6]" would work fine.
That should mean that fgets will also save str[6] for the \0 and str 0 - 4 would be for the 5 digit number
and str[5] would be for the \n, but this doesn't work, only if you change "char str[6]" to "char str[7]", but why???
*/
#include <stdio.h>
int main() {
int lp;
int cb;
char overflow = 'x'; //to make sure it doesn't get assigned something else when defined.
int input;
int nchars;
int returncode;
char str[6];
printf("Enter a 5 digit number:");
fgets(str, sizeof(str), stdin); //fgets will save str[6] for the \0
if (str[5] != '\n') {
printf("Not a 5 digit number\n");
for (lp = 0;lp < sizeof(str); lp++) {
if (str[lp] == '\n') {
overflow = 'F';
}
}
if (overflow != 'F') {
printf("Overflow = T\n");
while ((cb=getchar()) != '\n');
}
main();
}
//
for (lp = 0; lp < sizeof(str); lp++) {
if (str[lp] == '\n') {
str[lp] = '\0';
}
}
returncode = sscanf(str, "%d%n", &input, &nchars);
if (returncode != 1) main();
if ((returncode == 1) && (str[nchars] != '\0')) main();
else printf("Good job!");
getchar();
exit(0);
}