从标准输入读取各种输入

Reading various inputs from stdin

我正在读取标准输入。用户被提升为输入一个数字或输入三个。 这个问题哪些函数比较好?

我试过了

    int in[3] = {-1, -1, -1};
    scanf("%d %d %d", &in[0], &in[1], &in[2]);
    printf("%d, %d, %d\n", in[0], in[1], in[2]);

这适用于三位数字,但如果只输入一位数字则不行。

我想要例如输入为“17”或“0 1 9” 然后输出应该是例如

int amount = 1
int digits[3] = {17, -1, -1}

int amount = 3
int digits[3] = {0, 1, 9}

你接近你想要的,但是你读的是 int 而不是字符串 so

 char *in[3] = {-1, -1, -1};

必须

int in[3] = {-1, -1, -1};

还允许将 -1 作为有效初始值。

This works great for three digits but not if only one is typed.

scanf("%d %d %d", &in[0], &in[1], &in[2]); 完成你需要输入 3 个有效 int 或完成错误 ro 达到 EOF 或提供无效输入,只能输入一个值做一个 fgets 然后 _a __sscanf_

I want to have e.g. the input to be "17" or "0 1 9" The output should be then e.g.

int amount = 1
int digits[3] = {17, -1, -1}

or

int amount = 3
int digits[3] = {0, 1, 9}

举个例子

#include <stdio.h>

int main(void)
{
  char line[32];

  if (fgets(line, sizeof(line), stdin) == line) {
    int ints[3] = { -1, -1, -1 };
    int amount = sscanf(line, "%d %d %d", &ints[0], &ints[1], &ints[2]);

    printf("%d : { %d %d %d }\n", amount, ints[0], ints[1], ints[2]);
  }

  return 0;
}

编译与执行

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
pi@raspberrypi:/tmp $ ./a.out
17
1 : { 17 -1 -1 }
pi@raspberrypi:/tmp $ ./a.out
0 1 9
3 : { 0 1 9 }
pi@raspberrypi:/tmp $ ./a.out
1 a
1 : { 1 -1 -1 }
pi@raspberrypi:/tmp $ ./a.out
a
0 : { -1 -1 -1 }
pi@raspberrypi:/tmp $ 
pi@raspberrypi:/tmp $ ./a.out

-1 : { -1 -1 -1 }
pi@raspberrypi:/tmp $ 

(在最后一种情况下是一个空行,例如 enter

我将 digits 重命名为 ints 因为 digits 让我们假设每个条目都是一个数字 (例如'0')而你想要整数