What is the error in my program? This is the code:
/*
* courseProject.c
*
* It is a simple database for record shop
* to track its iventory of CDs
*
* by Mahmoud Emam, 2012.
*/
#include<stdio.h>
main()
{
/*
* CDs infrormations
*/
char title[31], artist[31];
short int numberOfTracks; /* short to save memory */
int albumOrSingle; /* Boolean to check 1 for Album and 0 for Single */
float price;
printf("Hello, Welcome to Record Shop!\n\n");
/*
* Asking for CD details
*/
printf("Enter CD details\n\n");
printf("CD's Title: ");
scanf("%[^\n]", title);
fflush(stdin);
printf("CD's Artist: ");
scanf("%[^\n]", artist);
printf("Number of tracks: ");
scanf("%d", &numberOfTracks);
printf("Please press \"1\" for album, \"0\" for single: ");
scanf("%d", &albumOrSingle);
printf("CD's Price: ");
scanf("%f", &price);
/*
* Output CD details
*/
printf("\nCD details:\n");
printf("=============\n\n");
printf("CD's Title: <%s>\n", title);
printf("CD's Artist: <%s>\n", artist);
printf("Number of tracks: <%d>\n", numberOfTracks);
if (albumOrSingle)
printf("This is <Album>\n");
else
printf("This is <Single CD>\n");
printf("Its price = <%.2f>\n", price);
printf("=============\n\n");
/* Exit from program */
printf("Press any key to exit\n");
fflush(stdin);
getchar();
}
This is a simple program that reads CD info from the user and outputs the details again on the screen. However, the artist variable is always empty. Why?
I made printf("%s", artist); after I read it from the user and it works correctly, but it doesn’t work at the end of the program. The variable is always empty.
The variable
numberOfTracksis ashort int, but you are reading it withscanf‘s%dspecifier, which reads anint. This leads to undefined behavior – in this case it probably overwrites other variables such asartist.Either use the
%hdspecifier (which reads ashort int), or change the variable to anint.