【发布时间】:2014-08-14 06:11:05
【问题描述】:
我到处检查,浪费了大约 3 个小时来寻找解决方案。我的程序本身就是无限循环。这是我的 C 程序:
#include <stdio.h>
#include <string.h>
int main (void)
{
int attempts = 0;
char password[10];
do
{
printf("Enter your password:\n");
scanf("%[^\n]s", password);
printf("\n");
attempts++;
} while (strcmp(password, "awesome 123 ok"));
printf("You entered a correct password in %d attempts!", attempts);
return 0;
}
我试过scanf("%[A-Za-z0-9 ]s", password)"所以它可以将包括空格在内的所有字符和数字作为输入,但它只是循环。而且我还尝试使用getchar(),但即使我输入正确的密码,它也会一次又一次地要求输入密码。任何帮助将不胜感激。
【问题讨论】:
-
您不需要
"%[^\n]s"格式的s。只使用"%[^\n]"。 -
强制:检查所有
scanf函数的返回值,始终。 -
检查一下你的 scanf 语法。可能你也可以使用gets(password)或者更正scanf("%[^\n]", password);
-
@Avinash 不不不,永远不要建议任何人使用
gets。它容易出现缓冲区溢出,在 C 标准中已被弃用很长时间,甚至在最新的 C11 标准中被删除。 -
@Avinash 永远不要使用
gets!它已损坏,已弃用,最终在 C11 中删除。例如使用fgets或非标准getline。
标签: c scanf infinite-loop