Scanf("%c %f %d %c") 返回奇怪的值 [英] Scanf("%c %f %d %c") Returning weird values
问题描述
我的课堂作业要求我提示用户在一个输入行中输入四个变量,char float int char.
My class assignment asks me to prompt the user to input four variable, char float int char, in one input line.
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
int main(void){
char h = 'a';
char b, c, d, e;
int m, n, o;
float y, z, x;
short shrt = SHRT_MAX;
double inf = HUGE_VAL;
printf("Program: Data Exercises\n");
printf("%c\n", h);
printf("%d\n", h);
printf("%d\n", shrt);
printf("%f\n", inf);
printf("Enter char int char float: ");
scanf("%c %d %c %f", &b, &m, &c, &y);
printf("You entered: '%c' %d '%c' %.3f \n", b, m, c, y);
这部分代码是我遇到问题的地方.
This section of code is where I am having the issue.
printf("Enter char float int char: ");
scanf("%c %f %d %c", &d, &z, &n, &e);
printf("You entered: '%c' %f %d '%c' \n", d, z, n, e);
如果我隔离上述部分,这部分工作.
This part works if I isolate the above section.
printf("Enter an integer value: ");
scanf("%d", &o);
printf("You entered: %15.15d \n", o);
printf("Enter a float value: ");
scanf("%f", &x);
printf("You entered: %15.2f \n", x);
return 0;
}
由于代表不够高而无法发布图片,我将在运行程序时提供指向控制台屏幕截图的链接.
Seeing as I cannot post images due to not having a high enough rep, I will provide a link to a screen-cap of the console when running the program.
如果有人能向我解释为什么程序无法正常工作,我将不胜感激.提前致谢.
I would really appreciate if someone could explain to me why the program is not working correctly. Thanks in advance.
推荐答案
你在这一行有一个错误:
You have an error in this line:
scanf("%c %d %c %f", &b, &m, &c, &y);
%c
前需要加一个空格.
试试这一行
You need to add one space before %c
.
Try this line
scanf(" %c %d %c %f", &b, &m, &c, &y); // add one space %c
scanf(" %c %f %d %c", &d, &z, &n, &e);
这是因为输入数字并按回车后,新行会留在缓冲区中,并会被下一个scanf
处理.
This is because after you input the number and press ENTER, the new line stays in the buffer and will be processed by the next scanf
.
这篇关于Scanf("%c %f %d %c") 返回奇怪的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!