提问人:Jennieee 提问时间:7/27/2023 最后编辑:Jennieee 更新时间:7/27/2023 访问量:43
如何在读取 3 的扫描中输入 2 个变量 [已关闭]
How to Input 2 Variables in a scanf that reads 3 [closed]
问:
所以,我想要一个输入,它可以接受不同变量(int 和 char)的 3 个输入。但是我想要一个选项,即使只给出 2 个变量,输出也会打印出一些东西。我如何使用 scanf 实现这一点,如果可能的话,它具有基本的 C 而不使用 Ctrl+D 并且不太高级,谢谢。
#include <stdio.h>
int main(void) {
char y;
int i;
int x;
int a;
printf("Enter Input: ");
a = scanf("%c %d %d", &y, &i, &x);
if(a == 2) {
printf("%c %d", y, i);
}
}
答:
3赞
Oka
7/27/2023
#1
避免常见陷阱的一般建议是使用 读取整行输入,然后使用(或使用遵循相同模式的工具,例如 (POSIX) + / / 等)在内存中解析这些行。scanf
fgets
sscanf
getline
strspn
strcspn
strtol
与在未完成转换且未达到 EOF(或错误)时等待更多输入的方式不同,它不会等待未完成的转换,因为不会突然有更多的字符串需要解析。scanf
stdin
sscanf
#include <stdio.h>
int main(void) {
char buffer[256];
printf("Enter Input: ");
if (!fgets(buffer, sizeof buffer, stdin))
return 1;
char y;
int i;
int x;
int rc = sscanf(buffer, "%c%d%d", &y, &i, &x);
if (rc < 2)
return 1;
if (rc < 3)
printf("%c | %d\n", y, i);
else
printf("%c | %d | %d\n", y, i, x);
}
用法示例:
% ./a.out
Enter Input: a 2
a | 2
% ./a.out
Enter Input: a 2 4
a | 2 | 4
评论
scanf()
fgets()
sscanf()
%c
scanf
'\n'