简体   繁体   中英

Issue with recursion in C++

Why is it not counting properly? I'm so confused why is it printing the string with 0's in it? I just want to count the number of uppercase letters and output them.

#include <iostream>

void uppercase(const char *str){
    //std::vector<char> strVector;
    int counter = 0;
    if(str[0]){
        if(isupper(str[0])) counter++;
        uppercase(str+1);
    }
     std::cout<<counter;
}
int main(){
   uppercase("United States of America");

}

the output:

0000000100000000010000001

The main issue in your function is that you are printing out whether a char is uppercase or not. Instead, you should make the function return an int , and recursively call the function with the next substring:

int uppercase(const char *str) {
    if(str[0]) {                    // while not reached the end of the string 
        return !! isupper(str[0])   // add 1 if uppercase 
               + uppercase(str+1);  // recursively call with suffix of string
    }
    return 0;  // base case
}

and now you can simply print the returned result:

int main(){
  std::cout << uppercase("United States of America");
}

Here's a demo .

Note that the !! is just a shorter syntax that converts the result if isupper to a bool and then back to an int . This is equivalent to isupper(str[0]) ? 1 : 0 isupper(str[0]) ? 1 : 0 .

Your calculation function should be doing just that: calculating (ie not printing anything ). Instead, it should return the number and have the original caller take the final step of printing.

Eg

#include <iostream>

int uppercase(const char *str)
{
    if (*str) 
        return (isupper(*str) ? 1 : 0) + uppercase(str+1);
    return 0;
}

int main()
{
   std::cout << uppercase("United States of America") << '\n';
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM