简体   繁体   English

使用循环反转c中的字符串…

[英]Reversing String in c using loops…

I have created a code reverse a string but for some reason it is not working. 我创建了一个将字符串反向的代码,但是由于某种原因它无法正常工作。 But I think my logic is right. 但是我认为我的逻辑是正确的。 Then why is it not working?? 那为什么不起作用呢?

#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]!='\0') {
           ++i;
    }
    printf("\nThe Reverse is: ");
    while (i<=0) {
         printf("%s",words[i]);
         i--;
     }
     return 0;
}

While you already have an answer, there are a few additional points you need to consider before you have a solution that doesn't have the potential to invoke Undefined behavior . 尽管您已经有了答案,但是在解决方案没有可能调用Undefined behavior的解决方案之前,还需要考虑其他几点。

First, always, always validate all user input. 首先, 始终要始终验证所有用户输入。 For all you know a cat could have gone to sleep on the 'L' key (with millions being entered), or a more likely case, the user just decides to type a 100-char sentence (or more) which leaves 'words' as an array of chars that is NOT nul-terminated and thus not a valid string in C. Your loop to get the length now invokes Undefined Behavior by reading beyond the end of words off into the stack until the first random '0' is encounter or a SegFault occurs. 就您所知,猫可能已经按过'L'键(输入了数百万条)或者更可能的情况入睡,用户只决定键入一个100个字符的句子(或更多),留下“单词”作为一个非零终止 的char数组,因此在C中不是有效的字符串 。获取长度的循环现在通过将超出words末尾的内容读入堆栈,直到遇到第一个随机“ 0”,从而调用Undefined Behavior或发生SegFault

To prevent this behavior (you should really just use fgets ) but with scanf you can provide a field-width modifier to prevent reading more than length - 1 chars. 为了防止这种行为(您实际上应该只使用fgets ),但是使用scanf您可以提供一个field-width修饰符,以防止读取的length - 1超过length - 1字符。 This insures space for the nul-terminating character. 这确保了零终止字符的空间。

Further, the "%s" conversion-specifier stops conversion on the first whitespace character encountered -- making your "Enter a .../sentence" an impossibility because scanf ("%s", words) will stop reading after the first word (at the first whitespace . 此外, "%s" 转换说明符会停止对遇到的第一个空格字符的转换-使得"Enter a .../sentence"成为不可能,因为scanf ("%s", words)将在第一个单词之后停止读取(在第一个空白处

To correct this problem (you should really just use fgets ) or with scanf you can use a character class (stuff between [...] ) as the conversion specifier that will read until a '\\n' is encountered., eg scanf ("%[^\\n]", words) . 要解决此问题(您实际上应该只使用fgets )或使用scanf您可以使用字符类 (介于[...]之间的东西)作为转换说明符 ,它将一直读取直到遇到'\\n' 。例如, scanf ("%[^\\n]", words) However, recall, that is still not good enough because more than 99-chars can be entered leaving the string un-terminated at 100 and invoking Undefined Behavior at character 101 (off the end of the array). 但是,回想起来,这仍然不够好,因为可以输入超过99个字符,从而使字符串在100处不终止,并在字符101处(数组末尾)调用Undefined Behavior

To prevent this problem (ditto on fgets ), or include the field-width modifier, eg scanf ("%99[^\\n]", words) . 为避免此问题( fgets同上),或包括字段宽度修饰符,例如scanf ("%99[^\\n]", words) Now no more than 99-chars will be read regardless of the cat sleeping on the 'L' key. 现在,无论猫在'L'键上睡觉时,最多只能读取99个字符。

Putting that altogether, you could do something like: 综上所述,您可以执行以下操作:

#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;
}

Example Use/Output 使用/输出示例

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

Look things over and let me know if you have any further questions. 仔细检查一下,如果您还有其他问题,请与我联系。

There are few mistakes in your program. 您的程序中几乎没有错误。

  1. After you have reached the end of the string.You should do i-- as your array index of i will be pointing to '\\0' . 到达字符串末尾后,应该执行i-因为i的数组索引将指向'\\0'

  2. Your while loop checks for <= but it should be >= . 您的while循环检查<=但应为>=

  3. Use %c for printing chararcters. 使用%c来打印字符。 %s is used to print strings and not char. %s用于打印字符串而不是char。


#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]!='\0') {
        ++i;
    }
    i--;
    printf("\nThe Reverse is: ");
    while (i>=0) {
       printf("%c",words[i]);
       i--;
    }
 return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM