Why does this c code not generate the expected result?

I wrote this simple c code in microsoft visual C ++ 2010.

#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(); } 

It means that

 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 

I cannot understand why it is not waiting for input for a type variable? Can someone explain this please? Thanks in advance.

+4
source share
4 answers

Instead

 scanf("%c",&type); 

Do you want to

 scanf(" %c",&type); 

Otherwise, one of the newline characters from the previous line will be used as a type.

+7
source

When you use scanf to read in a line, it reads only one word. This single word excludes the newline character ( "\n" ). When you follow this with scanf to read a single character, as you do, with type , the newline character will be the display character.

You can fix this by adding a space before %c , which will ignore any spaces (see http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ ): scanf(" %c",&type)

0
source

Add getchar() after scanf("%s",artist); to get extra \n (or \r\n ).

0
source

"\ n" from the previous scanf is processed for type

0
source

All Articles