如何获取接受浮点数或字符作为值的 C 输入

问题描述 投票:0回答:1

正如我所说,我需要能够接受字符 a b c d e 作为输入,但它也需要能够接受任何浮点数。我不确定这是否可能,但如果有人知道一个简单的解决办法,我将非常感激。我不想使用任何输入来询问用户他们将事先输入什么数据类型。

c input char calculator
1个回答
0
投票

最简单的方法是使用 fgets() 将用户输入的

读取到字符串中,然后以多种方式解析它。

使用

" %n"
记录扫描的偏移量,如果扫描到了那么远即可检测到成功并查找尾随垃圾。

// Read input as a,b,c,d,e or a float
// Return 2: if float
// Return 1: if char
// Return 0: neither
// Return EOF: end-of-file
int read_char_or_float(char *ch, float *f) {
  char buf[100];
  if (fgets(buf, sizeof buf, stdin) == NULL) {
    return EOF;
  }
  int n = 0;
  char s[2];
  // Scan for white-space, one_a_to_e, white-space
  sscanf(buf, " %1[a-e] %n", s, &n);
  if (n > 0 && buf[n] == '\0') {
    *ch = s[1];
    return 1;
  }

  n = 0;
  // Scan for white-space, float, white-space
  sscanf(buf, " %f %n", f, &n);
  if (n > 0 && buf[n] == '\0') {
    return 2;
  }

  return 0;
}

更好的代码会使用

strtof()
来解析
float
,但需要一些东西来开始 OP。

© www.soinside.com 2019 - 2024. All rights reserved.