英文:
How to Input 2 Variables in a scanf that reads 3
问题
所以,我想要一个输入,它可以接受3个不同变量(int和char)。但我希望有一个选项,即使只提供2个变量,也能打印出一些内容。如何使用scanf实现这一点,如果可能的话,使用基本的C语言,而不使用Ctrl+D,也不要太高级,谢谢。
#include <stdio.h>
int main(void) {
char y;
int i;
int x;
int a;
printf("输入:");
a = scanf("%c %d %d", &y, &i, &x);
if (a >= 2) {
printf("%c %d", y, i);
}
}
英文:
So, I want to have an input where it can take 3 inputs of different variables (int and char). But I want to have an option where an output prints out something even if only 2 variables are given. How do I make this possible using scanf and if possible something that has basic C whilst not using Ctrl+D and not too advanced, Thanks.
#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);
}
}
答案1
得分: 3
避免常见的 scanf
陷阱的一般建议是改为使用 fgets
读取完整的输入行,然后在内存中使用 sscanf
解析这些行(或使用遵循相同模式的工具,例如 getline
(POSIX)+ strspn
/ strcspn
/ strtol
等)。
与 scanf
在未满足转换条件并且 stdin
未达到 EOF(或出错)时等待更多输入的方式不同,sscanf
不会等待未满足的转换条件,因为不会突然有更多字符串需要解析。
示例用法:
% ./a.out
Enter Input: a 2
a | 2
% ./a.out
Enter Input: a 2 4
a | 2 | 4
英文:
The general advice for avoiding common pitfalls with scanf
is to instead read entire lines of input with fgets
, and then parse those lines in-memory with sscanf
(or use tools that follow the same pattern, e.g., getline
(POSIX) + strspn
/ strcspn
/ strtol
, etc.).
Unlike how scanf
waits for more input when it has an unfulfilled conversion and stdin
has not reached EOF (or error), sscanf
does not wait on an unfulfilled conversion because it is not like there will suddenly be more string to parse.
#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);
}
Example usage:
% ./a.out
Enter Input: a 2
a | 2
% ./a.out
Enter Input: a 2 4
a | 2 | 4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论