When I compile this program I only get the first capital letter but not the rest.
ABldjfdslkjfCK
I only get 'A' that is it?
#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;
}
You never increment the value of index
. Furthermore, you do not call the function recursive
if the current character is a capital letter, so the function just returns.
Rather than using a static variable for index
, it would be better to pass it in as an argument to recursive
; otherwise, the function is non-reentrant.
your recursive function calls to itself only if it finds a non capital character. when it finds the first capital character it prints it and quits
Your current function prints only A
because as soon as it finds an uppercase letter ( A
in your case) it returns a 0.
There are other issues too, so I would rewrite the function like this:
#include <ctype.h> /* for isupper */
void recursive(const char* s)
{
/* stop condition: empty string */
if (s[0] == '\0')
return;
/* main body: print letter if capital */
if (isupper(s[0]))
printf("%c\n", s[0]);
/* recursion: advance to the next character */
recursive(s + 1);
}
Use it like this: recursive(input)
.
Among the other issues that your recursive function has is that the index
variable is static. That's not a problem in the current versions, since you don't actually use it except in a trivial way. But once you try to fix the other problems (which may result in you using index
in s more complicated way), having it static
will pose a couple problems:
Two problems:
我看到的第一个错误是您永远不会增加索引。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.