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

标签 c scanf

我正在编写(至少尝试嘿)一个函数,您可以读取 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/

相关文章:

c - 'calloc' 不会自动消耗 RAM 中的内存

c++ - 我的动态数组在 free() 时有 SIGSEGV,但可以访问吗?

c - 使用 scanf 和 scanset 读取具有多个小数的 CSV

ocaml - 接收 Stdlib.Scanf.Scan_failure : character '\\n'

c - 如何确保父进程先于子进程执行scanf()?

c - Win32 (C) 应用程序在一些 GetWindowText 后卡住?

c - 为什么代码会抛出段错误?

c++ - Tcpdump - pcap - 无法嗅探端口 5984 上的数据包

c - 为什么在Eclipse中的printf之前执行scanf?

c - 如何从终端用 C 语言逐行读取文件?