2010-12-09 84 views
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(); 
    } 

这个简单的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 

我不明白为什么它不等待输入类型的变量?有人可以解释这个吗?提前致谢。

回答

7

而不是

scanf("%c",&type); 

你想

scanf(" %c",&type); 

否则,从以前的字符串的换行符一个将要消耗的类型。

+1

这工作,但你能解释我的逻辑吗?当我删除了额外的\ n,为什么问题没有解决? – narayanpatra 2010-12-09 16:43:17

+4

在读取要存储在`type`中的字符之前,scanf模式字符串的前导空格将导致scanf消耗所有空格(空格/返回/制表符/等)。 `%s`模式标记将跳过空白并读取一个字符串,然后*停止*在空白处(换行符),但是**不会消耗空白**,将其留在输入缓冲区中。因此你需要跳过这个空格; '%c'之前的空格将会这样做。 – cdhowie 2010-12-09 16:44:51

+0

感谢您的帮助。我明白了。 – narayanpatra 2010-12-09 16:51:27

0

当您使用scanf读取字符串时,它只读入一个单词。这个单词不包括换行符("\n")字符。当你按scanf关注这个单词时,你会用type来读取一个单独的字符,换行符将是被读取的字符。

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

0

添加getchar()scanf("%s",artist);,使多余的\n(或\r\n)将被占用后, 。

0

从前一个scanf'\ n'正在处理类型

相关问题