使用C语言的递归

Diy*_*Roy 1 c recursion

当我编译这个程序时,我只得到第一个大写字母而不是其余的.

输入:

ABldjfdslkjfCK

我只得到'A'就是这样吗?

#include <stdio.h>
#include <string.h>
FILE *fp;

int main(void)
{   
    int size; 
    char input[100]; // array size of 100 

    if (fp = fopen("message.txt","r")) // file exists
    {
        fgets(input,100,fp);// scans the sentence. 
    }
    else 
    {
    printf("file not found");// if there is no such a file. 
    }    

    size=strlen(input);  
    recursive(size,input); 

    return 0;
}

int recursive(int size, char array[])
{
    static int index = 0; // static so when the function is called, the  value is kept

    if (index < size) // start from index 0 until the size-1
    {
        if (array[index] >= 'A' && array[index] <= 'Z') // check for A to Z  (CAPITALIZE CHARACTERS only)
        {
            printf("%c\n", array[index]); // print it
        }
        else 
        {
            return recursive(size,array); // calls the function (recursion)
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 14

你永远不会增加值index.此外,recursive如果当前字符是大写字母,则不调用该函数,因此该函数只返回.

而不是使用静态变量index,最好将其作为参数传递给recursive; 否则,该功能是不可重入的.

  • 可重入 - http://en.wikipedia.org/wiki/Reentrant_%28subroutine%29(对于那些不记得它意味着什么的人,比如我:) (2认同)