Search code examples
c++functionrandomtoupper

Function to randomly convert chars toupper case


Am revisiting an exercise from an online course where we created a 'Whale translator' which checks through each character that the user inputs and extracts / returns only the vowels.

I thought it would be fun to have the returned values capitalized at random so the whole thing would feel a little like Dory speaking whale (finding Nemo) so I created a function to take each character and convert them to caps based on whether a random number is odd or even. Thing is that I cannot get the program to acknowledge or use my function. Runs fine otherwise.

Could somebody give me a pointer as to where I'm going wrong?

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

char converter(char);

int main() {

    std::cout << "WeELCooOmE ToOOoO the WHaALe translaAtoOor \n";

    std::cout << "\n PlEaAsE EnntEer yoOur text tOo beEE trAanslaAateEd \n\n";

    std::string input;

    std::getline(std::cin, input);

    std::cout << "\n";

    std::vector<char> vowels;

    vowels.push_back('a');
    vowels.push_back('e');
    vowels.push_back('i');
    vowels.push_back('o');
    vowels.push_back('u');

    std::vector<char> whale_talk;

    for (int i = 0; i < input.size(); i++) {

       for (int j = 0; j < vowels.size(); j++) {

            if (input[i] == vowels[j]) {


                whale_talk.push_back(input[i]);

            }

        }

    }

    std::cout << "HeEre iS yOoUr translaAtiOn..\n\n";

    for (int k = 0; k < whale_talk.size(); k++) { 

        converter(whale_talk[k]);
        std::cout << whale_talk[k];

    }

    std::cout << "\n";

}

char converter(char x) {     //function to convert characters toupper based on random number generation.                  

    int rando = rand() % 100;

    if (rando % 2 == 0) {

        x = toupper(x);
        return x;
    }

    else {

        return x;
    }
}

Solution

  • You converter function is returning the modified char but you never use the returned value in the for loop:

    converter(whale_talk[k]);
    

    You need to do:

    whale_talk[k] = converter(whale_talk[k]);
    

    Here's a demo.

    Alternatively, you can leave the call site as it is, but pass the char to be converted by reference, like this:

    void converter(char &x) {    // << pass by reference
     // and modify x, but don't return it
    }
    

    Here's a demo.