【发布时间】:2016-04-26 23:12:03
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char word[100];
while (word != "hello") {
system("clear");
printf("\nSay hello to me : ");
scanf(" %s", word);
}
printf("congrats, you made it !");
return 0;
}
在这段代码中:如果我输入除了你好之外的任何内容,循环继续。但是,输入 ENTER 键不会再次循环,只会添加一行。
我在某处读到使用 getchar() 可能会有所帮助,但我对 C 开发有点陌生,我被困在这里寻找几个小时如何使它工作。
编辑 0:
已删除
while (word != "hello")
char word[100];
scanf(" %s", word);
添加
#include <string.h>
while (strcmp(word, "hello") != 0)
char word[100] = {0};
fgets(word, 6, stdin);
编辑 1:
我试图在我的代码中包含类似的东西
fgets(word, 6, NULL);
但这让我遇到了分段错误。
**编辑2:**
正确的工作输入是:
fgets(word, 6, stdin);
所以它起作用了,但是在问题中添加了超过 6 个字符,例如:
Say hello to me : hello from the inside
只会打印:
Say hello to me :
Say hello to me :
所以我只是这样修改了函数:
fgets(word, 100, stdin);
但现在它不会让我有任何投入工作
【问题讨论】:
-
又是一行一行的样式 :) ……不知道这么丑是哪来的?
-
这段代码似乎没有将任何内容放入“word”中。您的 scanf 不应该使用 word 而不是 mot 吗?而且 mot 也没有定义。
-
您正在与
word != "hello"进行指针比较,这保证为假。你想要的是strcmp(word, "hello") != 0 -
请不要修改问题以应用任何建议的更改,因为这会使答案无效。相反,请评论更改是否有效。
-
关于“输入ENTER键不会再次循环”,不要使用
scanf(" %s",...。答案解释了“%s 格式说明符已经忽略了前导空格。”而是使用fgets()。