Rot13 实现:translate_string 函数错误

Rot13 implementation: error in translate_string function

我写了一个 rot13.c 程序,但我可以在 rot13_translate_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;
}

这里是主要部分(同一文件的一部分)- 我的 for i = 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;
 }

正如 Janis 所指出的那样,控制循环 do ... while。应该是
while( len >= 0 );

A "while" loop 运行s while the control expression is true (and terminate once the expression变为假)。您在循环之前定义变量 len 并且它不能是 <0.
所以你永远不会真正进入循环。

由于 fprintf(stdout, "%s\n", translation); 行,您为每个输入单词获得一行,其中您为每个(空)打印一行字 (\n).

在其他语言中,例如在 Pascal 中,有“repeat until”循环构造,它继续 运行 until 控制表达式为真,只有在它改变之后它才会终止。
在这种情况下,您可以使用 <0 的条件。 在 C 中,为了遵循相同的逻辑,您可以使用 while 循环 并否定条件。你的情况
} while (! (len < 0) );