为什么这个c代码没有产生预期的输出?

nar*_*tra 4 c visual-c++

我在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();
    }
Run Code Online (Sandbox Code Playgroud)

它出来了

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
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么它不等待类型变量的输入?有人可以解释一下吗?提前致谢.

cdh*_*wie 7

代替

scanf("%c",&type);
Run Code Online (Sandbox Code Playgroud)

你要

scanf(" %c",&type);
Run Code Online (Sandbox Code Playgroud)

否则,前一个字符串中的一个换行符将作为类型使用.

  • scanf模式字符串上的前导空格将导致scanf在读取要存储在`type`中的字符之前消耗所有空格(空格/返回/制表符/等).`%s`模式标记将跳过空格并读取字符串,然后在空格(换行符)处*停止*但**不会消耗空白**,将其留在输入缓冲区中.因此,您需要跳过这个空格; '%c`之前的空间会这样做. (4认同)