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

4

我已经在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();
    }

它的输出结果是:
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

我不明白为什么它不等待类型变量的输入?有人能解释一下吗?谢谢!

4个回答

7

与其

scanf("%c",&type);

you want

scanf(" %c",&type);

否则,前一个字符串中的换行符之一将被视为类型并被消耗。

1
这个可行,但能否请你解释一下逻辑?当我删除多余的 \n 后,为什么问题没有得到解决呢? - narayanpatra
4
scanf模式字符串中的前导空格将导致scanf在读取要存储在“type”中的字符之前消耗所有的空格/回车/制表符等空白符。 %s模式标记将跳过空格并读取一个字符串,然后停止在空格处(换行符),但不会消耗空格,而是将其留在输入缓冲区中。因此,您需要跳过这个空白符; 在%c之前的空格将实现这一点。 - cdhowie

0

当您使用scanf读取一个字符串时,它只会读取一个单词。这个单词不包括换行符("\n")。当您接着使用scanf读取单个字符,就像您正在对type进行的那样,换行符将是被读取的那个字符。

您可以通过在%c之前添加一个空格来解决这个问题,这将忽略任何空格(请参见http://www.cplusplus.com/reference/clibrary/cstdio/scanf/):scanf(" %c",&type)


-1 这将在换行符模式为CRLF的操作系统上彻底失败。 - cdhowie
@cdhowie 我刚刚忙着编辑那个:P @r.s.mahanti 试试更新。 - moinudin
为什么不按照我的答案使用 scanf(" %c", &type) 呢?前导空格将导致 scanf 消耗所有的空白字符。 - cdhowie
@cdhowie 好的,我不知道这一点,但你是对的,所以我改过来了。 - moinudin

0
scanf("%s",artist);后面添加getchar(),以便消耗多余的\n(或\r\n)。

那些使用“\r\n”模式作为换行符的操作系统怎么办? - cdhowie
对于使用“\r\n”的操作系统,stdin 已经将其转换为 \n。 - Joshua

0

前一个 scanf 中的 '\n' 正在被处理为类型


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接