Scanf(“%c%f%d%c”)返回奇怪的值

我的类赋值要求我提示用户在一个输入行中输入四个变量char float int char。

这是整个代码:

#include  #include  #include  #include  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); 

这部分代码是我遇到问题的地方。

  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); 

如果我将上述部分隔离,则此部分有效。

  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; } 

由于没有足够高的代表,因为我无法发布图像,所以在运行程序时,我将提供指向控制台屏幕截图的链接。

在此处输入图像描述

如果有人能向我解释为什么程序无法正常工作,我真的很感激。 提前致谢。

您在此行中有错误:

 scanf("%c %d %c %f", &b, &m, &c, &y); 

您需要在%c之前添加一个空格。
试试这一行

 scanf(" %c %d %c %f", &b, &m, &c, &y); // add one space %c scanf(" %c %f %d %c", &d, &z, &n, &e); 

这是因为在输入数字并按ENTER后,新行将保留在缓冲区中,并由下一个scanf

float值的输入在输入流中留下换行符。 当下一个scanf()读取一个字符时,它会获取换行符,因为%c不会跳过空格,这与大多数其他转换说明符不同。

您还应该检查scanf()的返回值; 如果您期望4个值并且它不返回4,那么您就遇到了问题。

并且,正如Himanshu在他的回答中所说,解决问题的有效方法是在格式字符串中的%c之前放置一个空格。 这会跳过空格,例如换行符,制表符和空格,并读取非空格字符。 数字输入和字符串输入自动跳过空格; 只有%c%[…] (扫描集)和%n不会跳过空格。