【发布时间】:2016-06-11 11:01:30
【问题描述】:
我试图简单地读取用户的输入并将 CD 记录存储到一些变量中。除了 char 的第二个数组 artist 没有打印任何内容之外,所有变量的所有变量详细信息都已正确打印出来。我试图通过在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);
}
【问题讨论】:
-
也许使用
%s不是一个好主意 - 请参阅 scanf - 假设某些标题是多个单词 -
只给第二个和第四个scanf语句空间
-
%s 连一个词都不能用,gets 和 puts 都证明了同样的问题
-
作为起点将
scanf(" %s", title);更改为scanf("%s", title); -
永远不要使用 scanf("%s", ..); (为什么有这么多初学者?)。最好使用 fgets(),或者使用 scanf("%"MAXLEN"s",...)。否则你会得到一个数组溢出和 UB 真的很快。
标签: c