gpt4 book ai didi

c - 在 C 中,我如何只接受某些字符串并继续要求用户输入直到输入有效输入?

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:18 24 4
gpt4 key购买 nike

我正在尝试用 C 编写一个简单的程序,它接受一个字符串并根据该输入执行一个操作。但是,如果用户输入了无效的字符串,我希望程序再次要求用户输入,直到用户提供有效的输入字符串。

示例输出:

P: Please enter a string.
U: runMarathon
P: Unable to process request, please enter a valid Input:
U: rideBike
P: Unable to process request, please enter a valid Input:
U: sayHello
P: Hello World.

我有一个这样的程序:

int num;

while (scanf("%d",&num) != 1 || num <= 0)
{
printf("Please enter an integer greater than 0\n");
fflush(stdin);
}

这个程序似乎有效;然而,一位经验丰富的 C 开发人员告诉我永远不要使用 fflush(stdin)。

这是我目前所拥有的:

int main()
{
char input[];
while (scanf("Please enter a command: %s\n",input))
{
printf("Your command is this: %s\n",input);
}
}

但是当运行这个方法时,当它接受输入后,程序只会不断地打印出来:

Your command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: HelloYour command is this: Hello

等等。令我惊讶的是,我找不到任何资源来解决看似简单的问题。我知道我可以使用 strcmp 来比较字符串,但是如何让 while 循环在再次打印响应之前等待用户输入?为什么我不能使用 fflush(stdin)?

欢迎任何意见,谢谢!

最佳答案

意外输入的问题在于 scanf 不会从输入缓冲区中删除该输入,因此下一次循环迭代时它会尝试读取相同的意外输入。

解决这个问题的最常见方法是阅读整行,例如fgets,然后对字符串使用sscanf

关于c - 在 C 中,我如何只接受某些字符串并继续要求用户输入直到输入有效输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com