【问题标题】:weird array string output奇怪的数组字符串输出
【发布时间】: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", &amp;title[i]) 应该是 scanf("%[^\n]s", title[i])author 和所有字符串 BTW 都是一样的
  • 首先最好粘贴一个工作程序 :-) 第二个问题在于您的scanf;因为您正在为titleauthor(由字符数组指定)输入字符串,所以scanf 中的它们前面不需要&amp;。正如@PaulR 所说,您不应该使用fflush(stdin) ...没有必要
  • 与您的问题无关,但您可能应该了解结构

标签: c arrays multidimensional-array


【解决方案1】:

问题是您永远不会终止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';
}

【讨论】:

  • 它工作正常。谢谢你的帮助!!我真的很感激
猜你喜欢
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多