gpt4 book ai didi

c - 如何访问 scanf 中最后读入的变量?

转载 作者:行者123 更新时间:2023-12-01 13:22:18 24 4
gpt4 key购买 nike

我正在编写(至少尝试嘿)一个函数,您可以读取 float 或整数等,并检查它是否是用户的有效输入。所以到目前为止我写了这段代码:

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>

int scancheck (const char *fmt, ...) {
int count, check, x = 1;
size_t len = strlen(fmt);
char *newfmt = malloc(len + 1 + 1 + 1);
strcpy(newfmt, fmt);
newfmt[len] = '%';
newfmt[len + 1] = 'c';
newfmt[len + 1 + 1] = '\0';
va_list ap;
do {
va_start (ap, newfmt);
check = (count = vfscanf(stdin, newfmt, ap));
if (check != strlen(newfmt) / 2) {
printf("Error\n");
fflush(stdin);
} else {
x = 0;
}
va_end (ap);
} while (x);
return count;
}

它有效,我可以读取数字,具体取决于我在调用该函数时使用的格式字符串。但是有一个大问题:如果我在号码后输入一个字母,它就会被接受。所以我用 %c 扩展了格式字符串。现在我想检查它是否等于“\n”,即您是否最后按下了 Enter 键。但是我不知道该怎么做,因为我无法访问该变量,因为它没有保存在任何地方而且我不知道如何保存它。我希望你能帮助我。提前致谢。

最佳答案

没有将变量添加到列表的简单方法 @Barmar , 缺少重新处理整个 fmt


建议改为使用 fgetc() 读取尾随字符。

int scancheck (const char *fmt, ...) {
va_list ap;
va_start (ap, fmt);
int count = vfscanf(stdin, fmt, ap);
va_end (ap);

if (count != EOF) {
// consume all trailing characters in the line
// Look for non-white-space
int non_white_space = 0;
int ch;
while ((ch = fgetc(stdin)) != EOF) {
non_white_space |= !isspace(ch);
if (ch == '\n') {
break;
}
}

if (non_white_space) {
printf("Error\n");
// or other error handling like `count = 0;`
}
}
return count;
}

Algorithmiker,我认为我们可以利用你的绝妙想法的萌芽来了解如何在一般情况下使用 scanf() 之类的函数并使用尾随字符,包括讨厌的尾随 '\n' 并检测是否发现任何违规(非空白)字符。

关于c - 如何访问 scanf 中最后读入的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41770787/

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