C 编程 - 用于由 space 分隔的 tkens 的 sscanf

C programming - sscanf for tkens separated by space

我目前正在尝试使用 C 编写一个程序(对 C 很陌生——只学了 2 周),我想通过标准输入从用户那里获取一串输入,其中该字符串具有一个字符,后跟 2 个浮点数(每个浮点数之间有 space)。例如:"y 2.1 1.1"。 我的问题是如何获取和存储这 3 个输入,同时确保第一个是字符,而后两个输入是浮点数?

坚持使用 sscanf(),但不要忘记检查其 return 值(查看 here)。输入 "y 1u 1" 真正发生的是 sscanf 将读取并存储有效的 char,然后它将读取并存储 int1,这是有效的,然后停止,因为"u"不匹配格式字符串。

下面是示例代码(使用 scanf() 而不是 fgets()sscanf())。

char in1;
int in2,in3;
int retval;

/*
char array[100] = {'[=10=]'};
fgets(array, 100, stdin);
retval = sscanf(array, "%c %d %d", &in1, &in2, &in3);
*/
retval = scanf("%c %d %d", &in1, &in2, &in3);

printf("Scanned %d items\n", retval);

printf("Here they come: ");
if(retval > 0) {
    printf("%c ", in1);
}
if(retval > 1) {
    printf("%d ", in2);
}
if(retval > 2) {
    printf("%d", in3);
}
putchar('\n');

How can I obtain and store the 3 inputs, while making sure the first is a char, and the following two inputs are ints?

problem with this code is that there are extra spaces at the very end, and I don't know how to get rid of it.

一个简单的使用sscanf()并检查扫描变量后是否有额外的anything的方法是使用"%n"记录位置在那一点扫描。

char in1;
int in2, in3;
int n = 0;
sscanf(array,"%c %d %d%n", &in1, &in2, &in3, &n);

if (n > 0 && (array[n] == '\n' || array[n] == '[=10=]')) {
  Success(in1, in2, in3);
}

检查 sscanf() 的结果总是很重要的。一种方法是检查其 return 值,此处应为 3。不幸的是,这并没有告诉我们 in3 之后是否存在任何内容。通过设置 n == 0 然后测试 n > 0,代码知道扫描一直成功地进行到 "%n"。代码还可以测试扫描停止的字符。