我们如何让用户在同一行输入三个不同的值。
像这样的东西:enter three numbers: 1, 2, 3
但是这三个都将存储在3个不同的变量中。
我试着这样做:
printf("Enter three numbers: ");
scanf("%d %d %d", one,two,three);
但这不起作用!
以下是整个代码:
#include <stdio.h>
int main(void) {
int one,two,three;
printf("Enter three numbers: ");
scanf("%d %d %d", &one,&two,&three);
printf("%d %d %d \n", one,two,three);
}
我尝试输入1, 2, 3
,我得到了这个:1 134513881 -1218503675
答案 0 :(得分:3)
scanf("%d %d %d", &one, &two, &three);
你很接近,但是scanf
并不关心这些变量的价值(这很好,因为它们很可能没有被初始化),它关心的是它们的地址所以它可以取消引用它们并写入内部。
答案 1 :(得分:0)
如果用例子中的逗号分隔数字,则逗号需要是格式字符串的一部分。检查scanf的返回以确认输入了三个字段。
#include <stdio.h>
int main(void) {
int one = 0,two = 0,three = 0, ch = 0;
printf("Enter three numbers separated by commas: ");
while ( ( scanf("%d ,%d ,%d", &one, &two, &three)) != 3) {
printf("Please enter three numbers separated by commas: ");
while ( ( ch = getchar ( )) != '\n' && ch != EOF) {
//clear input buffer
}
}
printf("%d %d %d \n", one,two,three);
return 0;
}
正如@MM所评论的那样,逗号前面带有空格的scanf格式"%d ,%d ,%d"
将允许逗号前面有任意数量的空格(包括无空格),以允许输入1,2,3
或{ {1}}。 1 , 2,3
也会跳过任何前导空格。