使用循环在 c 中反转字符串....

Reversing String in c using loops....

我已经创建了一个反转字符串的代码,但由于某种原因它不起作用。但是我觉得我的逻辑是对的。那为什么不行呢??

#include <stdio.h>
#include <stdlib.h>

int main() {
    char words[100];
    int i=0;
    printf("Enter a word/sentence: ");
    scanf("%s", words);

    while (words[i]!='[=10=]') {
           ++i;
    }
    printf("\nThe Reverse is: ");
    while (i<=0) {
         printf("%s",words[i]);
         i--;
     }
     return 0;
}

你的程序错误很少。

  1. 在你到达 string.You 的末尾后应该做 i-- 因为你的数组索引 i 将指向 '[=11=]'.

  2. 你的 while 循环检查 <= 但它应该是 >=.

  3. 使用%c打印字符。 %s 用于打印字符串而不是字符。


#include <stdio.h>
#include <stdlib.h>

int main() {
    char words[100];
    int i=0;
    printf("Enter a word/sentence: ");
    scanf("%s", words);

    while (words[i]!='[=10=]') {
        ++i;
    }
    i--;
    printf("\nThe Reverse is: ");
    while (i>=0) {
       printf("%c",words[i]);
       i--;
    }
 return 0;
}

虽然您已经有了答案,但在您拥有不会调用 未定义行为 的解决方案之前,您还需要考虑一些额外的要点。 =28=]

首先,总是,总是验证所有用户输入。 据您所知,一只猫可能会在 'L' 键上睡觉(输入数百万),或者更可能的情况是,用户只是决定输入一个 100 个字符的句子(或更多)留下 'words' 作为一个 字符数组 不是 nul-terminated 因此不是有效的 C 中的 string。您现在获取长度的循环调用 Undefined Behavior,方法是将超出 words 的末尾读入堆栈,直到第一个随机 '0 ' 遇到或发生 SegFault

为了防止这种行为(你真的应该只使用 fgets)但是对于 scanf 你可以提供一个 field-width 修饰符来防止阅读更多比 length - 1 个字符。这确保 space 用于 nul-terminating 字符。

此外,"%s" conversion-specifier 停止转换遇到的 第一个白色 space 字符 - - 让你的 "Enter a .../sentence" 成为不可能,因为 scanf ("%s", words) 将在第一个单词后停止阅读(在第一个 whitespace.

要纠正这个问题(你真的应该只使用 fgets)或者 scanf 你可以使用 字符 class(东西在 [...]) 之间作为 转换说明符 将读取直到遇到 '\n'。例如scanf ("%[^\n]", words)。然而,回想一下,这仍然不够好,因为可以输入超过 99 个字符,使字符串在 100 处未终止并在字符 101 处调用 Undefined Behavior(关闭大批)。

为了防止这个问题(同上 fgets),或者包含 field-width 修饰符,例如scanf ("%99[^\n]", words)。现在,无论猫睡在 'L' 键上,都不会读取超过 99 个字符。

总而言之,您可以执行以下操作:

#include <stdio.h>

#define MAXC 100    /* if you need a constant, define one */

int main(void) {

    char words[MAXC] = "";
    int i = 0, rtn = 0;     /* rtn - capture the return of scanf  */

    printf ("Enter a word/sentence : ");
    if ((rtn = scanf ("%99[^\n]", words)) != 1) {   /* validate ! */
        if (rtn == EOF)     /* user cancel? [ctrl+d] or [ctrl+z]? */ 
            fprintf (stderr, "user input canceled.\n");
        else                    /* did an input failure occur ? */
            fprintf (stderr, "error: invalid input - input failure.\n");
        return 1;               /* either way, bail */
    }

    for (; words[i]; i++) {}    /* get the length */

    printf ("Reversed word/sentence: ");
    while (i--)
        putchar (words[i]);     /* no need for printf to output 1-char */
    putchar ('\n');

    return 0;
}

例子Use/Output

$ ./bin/strrevloops
Enter a word/sentence : My dog has fleas.
Reversed word/sentence: .saelf sah god yM

检查一下,如果您有任何其他问题,请告诉我。