【问题标题】:reversing an array of strings in c [duplicate]在c中反转字符串数组[重复]
【发布时间】:2021-09-29 15:11:40
【问题描述】:

所以我试图反转一个字符串数组。该代码正在运行,但问题是:

  1. 在最后一次输入之后,我必须输入一个额外的字符(任何字符都可以)并按回车键以执行代码。

  2. 它在输出之前打印 2 个随机字符或 ??。 谁能解释一下为什么要打印那些??...

代码:

#include <stdio.h>

int     main(void)
{
    int     tot_books;
    int     i;
    int     j;

    scanf("%d\n", &tot_books);

    char    titles[tot_books][101];

    i = 0;
    while (i < tot_books)
    {
        scanf("%[^\n]\n", titles[i]);
        i++;
    }

    while (tot_books >= 0)
    {
        printf("%s\n", titles[tot_books]);
        tot_books--;
    }
    return (0);
}

输出:

7
Germinal
Le petit prince
Le meilleur des mondes
L'ecume des jours
L'Odyssee
Les miserables
Crime et Chatiment
d
��
Crime et Chatiment
Les miserables
L'Odyssee
L'ecume des jours
Le meilleur des mondes
Le petit prince
Germinal

【问题讨论】:

  • printf("%s\n", titles[tot_books]); 数组从零开始编号,有效索引为0 .. (tot_books-1)。打印循环的第一次迭代到达数组之外的一个。
  • 所以你需要在打印循环之前减少tot_book
  • scanf("%[^\n]\n", titles[i]); 替换为scanf("%[^\n]%*c", titles[i]); 以改善输入结束时的体验,但请确保检查返回值。 (不过fgets 会更好)

标签: c c-strings


【解决方案1】:

数组的索引从zerolength - 1

你需要:

    while (tot_books > 0)
    {
        printf("%s\n", titles[tot_books - 1]);
        tot_books--;
    }

第一个问题在重复链接中解释。

【讨论】:

  • 太棒了 ^^ 谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多