2

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;
}
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
Ashish Choudhary
  • 706
  • 1
  • 7
  • 18

3 Answers3

7

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;
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
  • i am new to this although this solve the prob but why do we use "std::" i mean i have been using turbo c++ and there i have not used it ever – Ashish Choudhary Aug 03 '16 at 05:54
  • 1
    when you put 'using namespace std;' there is no need to 'std::'. However, This consider usually as a bad behaviour :http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – Humam Helfawi Aug 03 '16 at 05:56
  • 3
    @AshishChoudhary: The trouble is that Turbo C++ is a very old C++ compiler, pre-dating the C++98 standard which introduced the `std::` notation for the standard library namespace. It is not a good C++ compiler to be learning with. – Jonathan Leffler Aug 03 '16 at 06:16
1

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

Duly Kinsky
  • 996
  • 9
  • 11
0

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;
}