Memory Rot13实现:translate_字符串函数中出错
我写了一个rot13.c程序,但我可以告诉你,在我的循环中,rot13\u translate\u字符串导致程序只打印出空行 有什么想法吗? 谢谢大家!Memory Rot13实现:translate_字符串函数中出错,memory,c,Memory,C,我写了一个rot13.c程序,但我可以告诉你,在我的循环中,rot13\u translate\u字符串导致程序只打印出空行 有什么想法吗? 谢谢大家! #include <stdio.h> #include <stdlib.h> #include <string.h> char rot13_translate_character(char c) { if( 'A' <= c && c <= 'M' ) {
#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;
}
这是同一个文件的主要部分,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所指出的,在循环中的控制是。。。虽然应该是 而len>=0
while循环在控制表达式为true时运行,并在表达式变为false时终止。在循环之前定义变量len,它不能是len-;}len<0;当len>=0;时,肯定应该是;。查看rot13\u translate\u字符串的定义将非常有用。还要注意,代码似乎假定表示字母的字符的代码是连续的,但C不能保证这一点。