Ashish Choudhary
Ashish Choudhary

Reputation: 726

converting uppercase letter to lowercase and vice versa for a string

I am trying to convert a string characters from uppercase to lowercase. There is no compilation error but I am still getting same output as input:

#include <iostream>
#include<string.h>
#include<ctype.h>
using namespace std;
int main() {
    char a[100];
    cin>>a;
    for(int i =0;a[i];i++){
        if(islower(a[i])){
            toupper(a[i]);
        }
        else if(isupper(a[i])){
            tolower(a[i]);
        }
    }
    cout<<a;
    return 0;
}

Upvotes: 2

Views: 3797

Answers (3)

Matt Champlin
Matt Champlin

Reputation: 1

Here's a solution I found by calling another char variable "charConvert" and setting it equal to the converted character.

#include <iostream>
#include<string.h>
#include<ctype.h>
using namespace std;

int main() {
    char a[100];
    cin >> a;
    char charConvert;

   for (int i = 0; a[i] ; i++) {

        if  (isupper(a[i])) { 
            charConvert = tolower(a[i]);
        }
        else if (islower(a[i])) {
            charConvert = toupper(a[i]);
        }
    }
    cout << charConvert << endl;

    return 0;
}

Upvotes: 0

Duly Kinsky
Duly Kinsky

Reputation: 996

You could use the transform function from the Standard Library with a lambda function that returns the uppercase or lowercase character of a given character.

#include <algorithm>
#include <iostream>

using namespace std;


int main
{
    string hello = "Hello World!";
    transform(hello.begin(), hello.end(), hello.begin(), [](char c){
            return toupper(c);})

    cout << hello << endl;
}

This would output HELLO WORLD!. You can imagine doing the same thing for lowercase

Upvotes: 1

Humam Helfawi
Humam Helfawi

Reputation: 20264

std::toupper , std::tolower functions do not work in-place. They return the result, so you have to assign it to a[i] again:

char a[100];
std::cin>>a;
for(std::size_t i =0;a[i];i++){
    if(std::islower(a[i])){
        a[i]=std::toupper(a[i]);// Here!
    }
    else if(std::isupper(a[i])){
        a[i]=std::tolower(a[i]);// Here!
    }
}
std::cout<<a;

Upvotes: 7

Related Questions