Search code examples
c++uppercaselowercase

uppercase to lowercase and vice versa


this code should convert uppercase to lowercase and vice versa .. the problem is its returning both upper and lower .. for example when i enter the word "tuna" it returns "TUNAtuna" .. help please

string rev_letter(string s)
{
    string word = s;
    string final_word="";
    char c;
    for(int i = 0 ; i<=(word.length()-1);i++)
    {
    c=word.at(i);
    if(isupper(c))
    {
        putchar(tolower(c));
        final_word+=c;
    }
    else
    {
        putchar(toupper(c));
        final_word+=c;
    }

    }
    return final_word;
} 

Solution

  • When you use putchar, you print the character as you expect (to the screen) but you don't put the character into final_word. In final_word, you actually put the initial word.

    Try this:

    string rev_letter(string s)
    {
        string word = s;
        string final_word="";
        char c;
        for(int i = 0 ; i<(word.length());i++)
        {
           c=word.at(i);
           if(isupper(c))
           {
               final_word+=tolower(c);
           }
           else
           {
               final_word+=toupper(c);
           }
        }
    
        return final_word;
    }