I'm trying to save input line by line storing it in a string. I need to be able to detect an empty line or a line that consists only of white spaces and print "ignored" if it happens. How do I do that? strlen(str) == 0 doesn't seem to work.
int getLine(char str[]) {
int i = 0;
int c;
while (i < N - 1 && (c = getchar()) != EOF && c != '\n') {
str[i] = c;
++i;
}
if (c == EOF) return 0;
str[i] = '\0';
return 1;
}
A line that contains only spaces is not empty. It's full of spaces.
There's a number of ways to do this. Hopefully this is clear.
// Returns nonzero iff line is a string containing only whitespace (or is empty)
int isBlank (char const * line)
{
char * ch;
is_blank = -1;
// Iterate through each character.
for (ch = line; *ch != '\0'; ++ch)
{
if (!isspace(*ch))
{
// Found a non-whitespace character.
is_blank = 0;
break;
}
}
return is_blank;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With