gpt4 book ai didi

c - 奇怪的数组字符串输出

转载 作者:行者123 更新时间:2023-11-30 20:35:04 25 4
gpt4 key购买 nike

我是 C 语言新手,我想创建一个库,输入的内容是标题、作者和书籍的出版年份。输出为书架代码(简称书名)、图书代码(书名首字母和作者首字母)、书名、作者和图书出版年份。如果我在标题中输入“C 如何编程”,那么货架代码应该打印“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]);

}

}

最佳答案

问题是您永远不会终止 shelf[][] 中的字符串,并且您没有正确跟踪 shelf[i][] 中的索引。 (也不清楚在哪里声明 ij。)尝试使用这个内部循环:

for (i = 0; i < 2; i++)
{
int k = 0;

for (j = 0; j < strlen(title[i]); j++)
{
if (j == 0 || title[i][j - 1] == ' ')
{
shelf[i][k++] = title[i][j];
}
}

shelf[i][k] = '\0';
}

关于c - 奇怪的数组字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40510929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com