我试图简单地读取用户的输入并将 CD 记录存储到一些变量中。除了 artist
的第二个 char
数组没有打印任何内容外,所有变量的所有变量详细信息都已正确打印出来。我试图通过在 scanf()
中的每个格式化字符串的前面引入空格来处理额外的字符间距,但这并没有解决它。
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price);
int main()
{
char title[61];
char artist[41];
short noOfTracks = 0;
int isAlbum = 0;
float price = 0.0;
char albumOrSingleResponse;
printf("Please enter the title: ");
scanf(" %s", title);
printf("Please enter the artist: ");
scanf(" %s", artist);
printf("Please enter the number of records: ");
scanf(" %d", &noOfTracks);
printf("Please enter whether or not the cd is an album/single (A or S): ");
scanf(" %c", &albumOrSingleResponse);
if(albumOrSingleResponse == 'A')
{
isAlbum = 1;
}
printf("Please enter the price of the CD: ");
scanf(" %f", &price);
displayCDInfo(title, artist, noOfTracks, isAlbum, price);
return 0;
}
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price)
{
printf("\nThe title of the CD is %s", title);
printf("\nThe name of the artist is %s", artist);
printf("\nThe number of tracks on this CD are %d", noOfTracks);
printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single");
printf("\nThe price of the cd is $%.2f", price);
}
最佳答案
这会起作用。只需将 char 数组声明的位置从主体顶部移动即可。
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price);
int main()
{
short noOfTracks = 0;
int isAlbum = 0;
float price = 0.0;
char albumOrSingleResponse;
char title[61];
char artist[41];
printf("Please enter the title: ");
scanf(" %s", title);
printf("Please enter the artist: ");
scanf(" %s", artist);
printf("Please enter the number of records: ");
scanf(" %d", &noOfTracks);
printf("Please enter whether or not the cd is an album/single (A or S): ");
scanf(" %c", &albumOrSingleResponse);
if(albumOrSingleResponse == 'A')
{
isAlbum = 1;
}
printf("Please enter the price of the CD: ");
scanf(" %f", &price);
displayCDInfo(title, artist, noOfTracks, isAlbum, price);
return 0;
}
void displayCDInfo(char* title, char* artist, short noOfTracks, int isAlbum, float price)
{
printf("\nThe title of the CD is %s", title);
printf("\nThe name of the artist is %s", artist);
printf("\nThe number of tracks on this CD are %d", noOfTracks);
printf("\nThe CD is an %s", (isAlbum == 1) ? "album" : "single");
printf("\nThe price of the cd is $%.2f", price);
}
关于c - Printf 和 Scanf 对于第二个字符串输入无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762957/