The obvious way would be something like:
if (input[0] != '\0')
printf("hi");
Although using strlen
will work, it's potentially quite wasteful -- it turns an O(1) operation into O(N).
Of course, you nearly always want to start by checking the return value from fgets
first. Then if it says it succeeded at reading something, you check the content to be sure it's not empty.
Here's a quick demo of catching most of what can happen:
#include <stdio.h>
#include <string.h>
int main()
{
char input[10];
printf("Enter :");
if (!fgets(input, sizeof(input), stdin)) {
printf("fgets failed\n");
return 0;
}
char *pos = strchr(input, '\n');
if (pos != NULL) {
printf("Removing new-line\n");
*pos = '\0';
}
if(input[0] == '\0') {
printf("empty input");
} else {
printf("Read input: \"%s\"", input);
}
return 0;
}
[Note: I've shortened the input size from 1000 to only 10 characters so it's easy to see what happens when you enter more input than you've allowed fgets
to read.]
- If you press (only) ctrl+d (Linux) or F6 (Windows), you should get the "fgets failed" message.
- If you just press Enter, you should get the "empty input" message.
- If you enter a string of less than 10 characters, you should get "removing new-line" followed by a display of the string you entered.
- If you enter a string of 10 or more characters, you should get a display of the first 9 characters of the string you entered (but not the "Removing new-line" message).
input
came from. Thestrlen
function just searches for the first'\0'
in the string, so by definitioninput[strlen(input) - 1] == '\0'
. The only thing it could change is the introduction of a segfault ifinput
isn't null-terminated, and doesn't happen to be followed by any'\0'
s before running out of your program's address space. – Falconry