C语言中fgets获取字符串后多次打印
fgets in C language multiple prints after get string
我有那个代码,我希望我的循环在用户输入“###”时结束。
int main(){
char s[10];
printf("Give string: ");
fgets(s,11,stdin);
do{
printf("Give string: ");
fgets(s,11,stdin);
}while ( s!="###" );
return 0;
}
到目前为止没问题,但是当用户输入大于 11 个字符时,我会打印多个 "Give String"。
我用 scanf
试了一下,我做对了。任何人都可以给我一个使用 fgets
的解决方案吗?
I mean the output looks like this.
C 字符串不支持直接比较,你需要 strcmp
,所以
while ( s!="###" )
应该是 while(strcmp(s,"###"))
您还需要从 fgets
中删除 \n
(以便 strcmp
忽略 \n
)。所以 do..while
应该是这样的:
do{
printf("Give string: ");
fgets(s,11,stdin);
s[strlen(s) - 1] = '[=10=]';
} while (strcmp(s,"###"));
我有那个代码,我希望我的循环在用户输入“###”时结束。
int main(){
char s[10];
printf("Give string: ");
fgets(s,11,stdin);
do{
printf("Give string: ");
fgets(s,11,stdin);
}while ( s!="###" );
return 0;
}
到目前为止没问题,但是当用户输入大于 11 个字符时,我会打印多个 "Give String"。
我用 scanf
试了一下,我做对了。任何人都可以给我一个使用 fgets
的解决方案吗?
I mean the output looks like this.
C 字符串不支持直接比较,你需要 strcmp
,所以
while ( s!="###" )
应该是 while(strcmp(s,"###"))
您还需要从 fgets
中删除 \n
(以便 strcmp
忽略 \n
)。所以 do..while
应该是这样的:
do{
printf("Give string: ");
fgets(s,11,stdin);
s[strlen(s) - 1] = '[=10=]';
} while (strcmp(s,"###"));