2015-03-31 72 views
1

我寫了一個rot13.c程序,但我可以告訴我的循環裏面有些東西rot13_translate_string導致程序只是打印出空行。Rot13實現:error_string函數中的錯誤

有什麼想法? 謝謝!

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

char rot13_translate_character(char c) 
{ 
    if('A' <= c && c <= 'M') 
    { 
      return c + 13; 
    } 
    else if('N' <= c && c <= 'Z') 
    { 
      return c - 13; 
    } 
    else if('a' <= c && c <= 'm') 
    { 
      return c + 13; 
    } 
    else if('n' <= c && c <= 'z') 
    { 
      return c - 13; 
    } 
    else 
    { 
      return c; 
    } 
} 

char *rot13_translate_string(const char *str) 
{ 
    int len   = strlen(str); 
    char *translation = calloc(len, sizeof(char)); 

    int i; 

    do //****HERE IN THIS SECTION 
    { 
      /* Translate each character, starting from the end of the string. */ 
      translation[len] = rot13_translate_character(str[len]); 
      len--; 
    } while(len < 0); //< 

    return translation; 
} 

這裏是主要的(同一個文件的一部分) - 是我的條件爲我= 1好嗎?

int main(int argc, char **argv) 
{ 
    if(argc < 2) 
    { 

      fprintf(stderr, "Usage: %s word [word ...]\n", argv[0]); 
      return 1; 
    } 

    /* Translate each of the arguments */ 
    int i; 
    for(i = 1; i < argc; i++)  //*****IS this right? 
    { 
      char *translation = rot13_translate_string(argv[i]); 
      fprintf(stdout, "%s\n", translation); 
    } 

    return 0; 
} 
+2

'len--; } while(len <0);'當然應該是'while(len> = 0);'。 – 2015-03-31 05:39:44

+0

查看「rot13_translate_string」的定義會很有用。還要注意,你的代碼似乎假定代表字母的字符的代碼是連續的,但C不能保證。 – dhag 2015-03-31 06:12:19

回答

0

正如剛纔它被詹尼斯指出的是環路控制做......而。它應該是
while(len >= 0);

「while」循環運行而控制表達式是真(並且終止一旦表達變爲假)。您在循環之前定義變量len並且它不能是<0
所以你從來沒有真正進入循環。

您獲得,因爲fprintf(stdout, "%s\n", translation);線各輸入字,在那裏你打印每個(空)字線(\n)一行。

在其它語言中,例如在帕斯卡,有「重複直到」環結構,它繼續運行直到控制表達式爲真,並且僅後,它改變它終止。
在這種情況下,您可以使用<0的條件。 在C遵循相同的邏輯,你可以使用而循環並取消條件。在你的情況下,
} while (! (len < 0));