gpt4 book ai didi

c - 如何接受 ";' 分号作为输入,而不执行下一行代码?

转载 作者:行者123 更新时间:2023-11-30 14:53:49 25 4
gpt4 key购买 nike

这是我正在做的防止错误输入的一小部分实践。

while(1) {
printf("Choose From 1 to 7 ");
if( scanf("%d", &nNum ) != 1) {
printf("Please only choose from the numbers 1-7.");
fgets(sErraticInputs, 100 , stdin);
} else if (nNum > 7 || nNum <= 0) {
printf("Please only choose from the numbers 1-7.");
} else {
break;
}
}

我做得很好,直到我输入“6;p”。它执行了第 6 部分并正确运行,但从技术上讲,它应该将整个内容作为输入,并继续处理错误消息。

最佳答案

首先,我认为发布的代码不能给出上述结果。当读取 6 时,break 语句将结束 while(1),因此不会打印错误消息。

如果我们假设 break 不是您真实代码的一部分,则会发生以下情况:

scanf 被告知读取一个整数时,只要下一个字符(与之前读取的字符一起)可以转换为整数,它就会继续从输入流中读取。一旦下一个字符不能用作整数的一部分,scanf就会停止并给出迄今为止它解析的结果。

在您的情况下,输入流包含

6;p\n

因此 scanf 将读取 6 并停止(即返回 6)。输入流现在包含:

;p\n

因此,这将是您下一个 scanf 的输入,并导致输入错误,您看到了。

解决此问题的一种方法是在 all scanf 之后刷新标准输入 - 无论成功还是失败:

nNum = 0;
while(nNum != 7) // Just as an example I use input 7 to terminate the loop
{
printf("Choose From 1 to 7 ");
if( scanf("%d", &nNum ) != 1 || nNum > 7 || nNum <= 0)
{
printf("Please only choose from the numbers 1-7.");
}
else
{
printf("Valid input %d\n", nNum);
// **************************** break;
}
fgets(sErraticInputs, 100 , stdin); // Always empty stdin
}

注意:使用大小为 100 的 fgets 并不能真正确保完全刷新...您实际上应该使用循环并继续,直到 '\n' 出现阅读。

通过上述更改,像 6;p 这样的输入将被视为值为 6 的有效输入,并且 ;p 将被丢弃。

如果这是 Not Acceptable ,您可以放弃使用 scanf 并自行进行解析。有多种选择,例如fgetsfgetc

下面的示例使用fgetc

#include <stdio.h>
#include <stdlib.h>

int get_next()
{
int in = fgetc(stdin);
if (in == EOF) exit(1); // Input error
return in;
}

void empty_stdin()
{
while(get_next() != '\n') {};
}

int main(void) {
int in;
int nNum = 0;
while(nNum != 7)
{
printf("Choose From 1 to 7 \n");
in = get_next();
if (in == '\n' || in <= '0' || in > '7') // First input must be 1..7
{
printf("Please only choose from the numbers 1-7.\n");
if (in != '\n') empty_stdin();
}
else
{
nNum = in - '0';
in = get_next();
if (in != '\n') // Second input must be \n
{
printf("Please only choose from the numbers 1-7.\n");
empty_stdin();
}
else
{
printf("Valid input: %d\n", nNum);
}
}
}
return 0;
}

此代码仅接受数字 (1..7) 后跟换行符

关于c - 如何接受 ";' 分号作为输入,而不执行下一行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46997128/

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