0

The code reverses the statement but it doesn't make the uppercase letters lowercase. I'm pretty new to coding and would appreciate some help, thanks! :

#include<iostream>
#include<cstring>
using namespace std;
int main ()
{
    char str[50], temp;
    int i, j, x;
    cout << "Enter a string : ";
    gets(str);
    j = strlen(str) - 1;
    int size =  strlen(str)-1;
    for (x=0;x<=size;x++){
    if (str[x]>'z'){
        str[x]+'32';
    }

    }
    for (i = 0; i < j; i++,j--)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    cout << "\nReverse string : " << str;
    return 0;
}

Johny Jim
  • 15
  • 3
  • `str[x]+'32'` This is just an expression that computes the sum of `str[x]` and `'32'` which is a `char` literal. Likely you meant to use `str[x] += 32` to assign the character at `str[x]` a new value which is equal to the old value of `str[x]` plus the number `32`? (Which btw is a not-so-great way of accomplishing what `std::toupper` will do much better.) Also, `str[x] > 'z'` is likely wrong. Try an `islower` test instead. – Wyck Dec 02 '19 at 01:59
  • 1
    Additional to what @Wyck said, your chdck `str[x]>'z'`makes no sense. You want to see if the letter is an uppercase letter? Use `if(str[x] >= 'A' && str[x] <= 'Z')`, or even better [`std::isupper`](https://en.cppreference.com/w/cpp/string/byte/isupper) – n314159 Dec 02 '19 at 02:02
  • Usually one would take a library function like `tolower` for case conversion. As written, the condition is incorrect. ASCII characters greatger than `z` are some special characters like `{ | } ~` – Phil1970 Dec 02 '19 at 02:04
  • Furthermore you should be using `std::string` in C++, not null-terminated C style strings based on `char*`. `gets` has been deprecated and removed from C and C++. It should never be used. Please learn C++ from a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). However you are learning it right now is not teaching you correctly. – walnut Dec 02 '19 at 02:05
  • Also, a tip: don't use `size = strlen(str) - 1` and compare `x <= size`. Instead use `size = strlen(str)` and compare `x < size`. You'll thank me the day you decide to use an unsigned int. – Wyck Dec 02 '19 at 02:06
  • The compiler should be giving you at least three warnings for your code: 1. the statement that does nothing, 2. the use of a multicharacter character literal, 3. the use of a deprecated/removed library function. If it doesn't [read here](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) why you should enable these warnings and how to do so. Don't ignore any warnings from the compiler and if you don't understand one you can ask about that specifically here if searching for prior questions doesn't give you an answer. – walnut Dec 02 '19 at 02:10

0 Answers0