Reputation: 445
I am trying to get the user to enter string in a loop unless the string is found to be empty.
This is my attempt and I tried couple of different ways but I have the same problem. the loop keeps going even when I don't enter any thing.
Code
char string[100];
do{
fgets(string,100,stdin);
} while (string[0] != '\0');
Unfortunately, when I run this the output is something like this:
Output
> hello
> world
> test
>
>
I also tried using scanf()
instead of fgets()
but the same issue is still there.
Upvotes: 1
Views: 569
Reputation: 33813
You can use strcmp
function to check whether the input is empty or not:
char str[50];
while(strcmp(gets(str), "") != 0){
printf("Output: %s\n", str);
}
strcmp
function returns 0 when both strings are found to be identical.
Upvotes: 0
Reputation: 8286
Using fgets
is pretty simple. As a feature, you can test to see it the input contains a newline. If not, there are pending characters.
scanf
is possible using a scanset. %99[^\n]
will scan up to 99 characters that are not a newline. %*c
will consume the newline. If the only character is a newline then the scanset will fail and scanf will return 0. If more than 99 characters are entered, %*c
will consume a character that is not a newline. fgets
does not have that problem.
#include <stdio.h>
int main ( void) {
char string[100] = "";
int result = 0;
printf ( "using fgets\nenter a blank line to stop\n");
do {
fgets ( string, sizeof string, stdin);
} while ( string[0] != '\n');
printf ( "using scanf\nenter a blank line to stop\n");
do {
result = scanf ( "%99[^\n]%*c", string);
} while ( result == 1);
return 0;
}
With ungetc
, if scanf reads too many characters, the last character can be put back in the stream if it is not a newline.
char last = 0;
do {
result = scanf ( "%99[^\n]%c", string, &last);
if ( EOF == result) {
fprintf ( stderr, "scanf EOF\n");
return 0;
}
if ( '\n' != last) {
ungetc ( last, stdin);
}
} while ( result == 2);
Upvotes: 1