簡體   English   中英

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

盡管您已經有了答案,但是在解決方案沒有可能調用Undefined behavior的解決方案之前,還需要考慮其他幾點。

首先, 始終要始終驗證所有用戶輸入。 就您所知,貓可能已經按過'L'鍵(輸入了數百萬條)或者更可能的情況入睡,用戶只決定鍵入一個100個字符的句子(或更多),留下“單詞”作為一個非零終止 的char數組,因此在C中不是有效的字符串 。獲取長度的循環現在通過將超出words末尾的內容讀入堆棧,直到遇到第一個隨機“ 0”,從而調用Undefined Behavior或發生SegFault

為了防止這種行為(您實際上應該只使用fgets ),但是使用scanf您可以提供一個field-width修飾符,以防止讀取的length - 1超過length - 1字符。 這確保了零終止字符的空間。

此外, "%s" 轉換說明符會停止對遇到的第一個空格字符的轉換-使得"Enter a .../sentence"成為不可能,因為scanf ("%s", words)將在第一個單詞之后停止讀取(在第一個空白處

要解決此問題(您實際上應該只使用fgets )或使用scanf您可以使用字符類 (介於[...]之間的東西)作為轉換說明符 ,它將一直讀取直到遇到'\\n' 。例如, scanf ("%[^\\n]", words) 但是,回想起來,這仍然不夠好,因為可以輸入超過99個字符,從而使字符串在100處不終止,並在字符101處(數組末尾)調用Undefined Behavior

為避免此問題( fgets同上),或包括字段寬度修飾符,例如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;
}

使用/輸出示例

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

仔細檢查一下,如果您還有其他問題,請與我聯系。

您的程序中幾乎沒有錯誤。

  1. 到達字符串末尾后,應該執行i-因為i的數組索引將指向'\\0'

  2. 您的while循環檢查<=但應為>=

  3. 使用%c來打印字符。 %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