曲径通幽论坛

标题: 递归--字符串的反转输出 [打印本页]

作者: beyes    时间: 2008-11-16 22:41
标题: 递归--字符串的反转输出
#include <stdio.h>
#include <string.h>

#define MAXSIZE  10

char string[MAXSIZE];
int length;

void reverse(int N)
{
    if(N < length)
    {
        reverse(N + 1);
        printf("%c",string[N]);
    }
}


int main(void)
{
    printf("Please enter string: ");
    //scanf("%s",&string);

    if( fgets(string,MAXSIZE,stdin) == NULL )
    {
        printf("Read error.\n");
        return 1;
    }

    length = strlen(string);
    printf("The String Length is %d\n",length);

    reverse(0);

    printf("\n");

    return -1;
}
               

说明:

在上面程序中,使用 fgets() 函数而不是 scanf 或者 gets 是基于 scanf 所接受的字符串会被空格阻挡 以及 gets函数是不安全的函数体考虑。gets 虽然可以接受空格,但是没有检查数组边界,一旦溢出,可能造成程序的崩溃。而 fgets函数则是安全的做法。如一个有10个元素的数组,fgets 接受输入 9 个字符,最后一个位置即 array[9] 放置 '\0' 作为结束符。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2