我已经写在Microsoft Visual C++ 2010为什么这个C代码不会产生预期的输出?
#include<stdio.h>
#include<conio.h>
void main()
{
char title[20], artist[30];
int numtrack, price;
char type;
printf("Enter the title of CD \n");
scanf("%s",title);
printf("\nName of the artist \n");
scanf("%s",artist);
printf("\nEnter the type of CD(enter a for album and s for single)\n");
scanf("%c",&type);
printf("\n Enter the number of tracks \n");
scanf("%d", &numtrack);
printf("\n Enter the price of the cd \n");
scanf("%d", &price);
printf("%s\n%s\n%c\n%d\n%d\n",title, artist, type, numtrack, price);
getch();
}
这个简单的C代码,它的出放为
Enter the title of CD
ranjit
Name of the artist
mahanti
Enter the type of CD(enter a for album and s for single)
Enter the number of tracks
4
Enter the price of the cd
4
ranjit
mahanti
4
4
我不明白为什么它不等待输入类型的变量?有人可以解释这个吗?提前致谢。
这工作,但你能解释我的逻辑吗?当我删除了额外的\ n,为什么问题没有解决? – narayanpatra 2010-12-09 16:43:17
在读取要存储在`type`中的字符之前,scanf模式字符串的前导空格将导致scanf消耗所有空格(空格/返回/制表符/等)。 `%s`模式标记将跳过空白并读取一个字符串,然后*停止*在空白处(换行符),但是**不会消耗空白**,将其留在输入缓冲区中。因此你需要跳过这个空格; '%c'之前的空格将会这样做。 – cdhowie 2010-12-09 16:44:51
感谢您的帮助。我明白了。 – narayanpatra 2010-12-09 16:51:27