【发布时间】:2016-11-09 15:48:40
【问题描述】:
我是 C 的新手,我想创建一个库,输入是标题、作者和图书的出版年份。输出是书架代码(缩短的书名)、书名(书名的首字母和作者的首字母)、书名、作者和书籍的出版年份。如果我在标题中输入“C How to Programming”,那么货架代码应该打印“CHtP”。问题是,当我打印货架代码时,我的程序中打印了奇怪的符号。请帮忙..
int main()
{
char title[5][200], author[5][200], shelf[5][200], bookcode[5][200], temp[200];
int year;
printf("Welcome to Blues Library\n");
printf("============================\n\n");
for(i = 0; i < 2; i++)
{
printf("Book's Title = ");
scanf("%[^\n]s", &title[i]); fflush(stdin);
printf("Book's Author = ");
scanf("%[^\n]s", &author[i]); fflush(stdin);
printf("Book's publishing year = ");
scanf("%d", &year); fflush(stdin);
printf("\n");
}
printf("\n");
for(i = 0; i < 2; i++)
{
for(j = 0; j < strlen(title[i]); j++)
{
if(j == 0)
{
shelf[i][j] = title[i][j];
}
else if(title[i][j-1] == ' ')
{
shelf[i][j] = title[i][j];
}
}
}
//print
for(i = 0; i < 2; i++)
{
printf("Book's Title = %s\n", title[i]);
printf("Book's Author = %s\n", author[i]);
printf("Book's publishing year = %d\n", year);
printf("Shelf Code = %s\n", shelf[i]);
}
}
【问题讨论】:
-
fflush(stdin)不好(未定义的行为)。 -
更糟糕的是:
scanf("%[^\n]s", &title[i])应该是scanf("%[^\n]s", title[i])。author和所有字符串 BTW 都是一样的 -
首先最好粘贴一个工作程序 :-) 第二个问题在于您的
scanf;因为您正在为title和author(由字符数组指定)输入字符串,所以scanf中的它们前面不需要&。正如@PaulR 所说,您不应该使用fflush(stdin)...没有必要 -
与您的问题无关,但您可能应该了解结构。
标签: c arrays multidimensional-array