I recently tried to use fgets()
instead of scanf()
to read a string for code security reasons. I used a simple function that I found here to check for errors (no input and too long input). The problem is that whenever i press "ENTER" without actually writing anything, fgets()
doesn't return NULL
and my program is not able to show the NO_INPUT
error.
Here's main.cpp
:
#include <stdlib.h>
#include <stdio.h>
#include "utilities.h"
int main() {
int rc;
char str[20];
rc = getLine("Enter string: ", str, sizeof(str));
if(rc == NO_INPUT) {
printf("[ERROR] No input\n\n");
} else if(rc == TOO_LONG) {
printf("[ERROR] Input is too long\n\n");
} else {
printf("This is your input: \"%s\"\n\n", str);
}
system("pause");
}
Here's utilities.h
:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
int getLine(const char *msg, char *buff, size_t len) {
if(msg != NULL) {
printf("%s", msg);
fflush(stdout);
}
if(fgets(buff, len, stdin) == NULL /*[+]*/ || strcmp(buff, "\n") == 0) {
//[-] fflush(stdin);
return NO_INPUT;
} else if(buff[strlen(buff)-1] != '\n') {
//[-] fflush(stdin);
return TOO_LONG;
} else {
buff[strlen(buff)-1] = '\0';
//[-] fflush(stdin);
return OK;
}
}
And here's the output:
Enter string: This is your input: "" Press any key to continue . . .
I solved my problem by replacing the first if
statement in utilities.h
with if(fgets(buff, len, stdin) == NULL || strcmp(buff, "\n") == 0)
. Doing this, my program will check for input errors OR for empty strings and return the NO_INPUT
flag.
Thanks to everybody who commented and @Peter for answering. I added the aforementioned if
statement in utilities.h
and removed every fflush(stdin)
occurrence. The code now looks as above.