Antreas Petsas Antreas Petsas - 21 days ago 8
C Question

fgets in C language multiple prints after get string

I have that code and I want my loop finish when user gives "###".

int main(){

char s[10];

printf("Give string: ");
fgets(s,11,stdin);
do{
printf("Give string: ");
fgets(s,11,stdin);
}while ( s!="###" );
return 0;
}


So far it's ok, but when the user gives an input bigger than 11 characters I have multiple prints of "Give String".
I try it with
scanf
and I did it right. Can anyone give me a solution to do it with
fgets
?
I mean the output looks like this.

Answer

C string doesn't support direct comparison, you would need strcmp for that, so

while ( s!="###" ) should be while(strcmp(s,"###"))

Also you'd need to remove \n from fgets (so as strcmp to ignore \n). So the do..while should look like:

do{
    printf("Give string: ");
    fgets(s,11,stdin);
    s[strlen(s) - 1] = '\0'; 
} while (strcmp(s,"###"));
Comments