Casper LI Casper LI - 1 month ago 23
C++ Question

No conversion from "const char" to "int"

The following is the problem code.

#include <iostream>
#include <cctype>
using namespace std;

void convertToUppercase(char *);

int main()
{
char phrase[] = "characters and $32.98";

cout << "The phrase before conversion is : " << phrase;
convertToUppercase(phrase);
cout << "\nThe phrase after conversion is : " << phrase << endl;
return 0;
}

void convertToUppercase(char *sPtr)
{
while (*sPtr != "\0")
{
if (islower(*sPtr))
*sPtr = toupper(*sPtr);

cout << "sPtr (before) = " << sPtr;
sPtr++;
cout << "\nsPtr (after) = " << sPtr << endl;
}
}


The output window shows me that :

1>d:\sync files\converting lowercase letter to uppercase letters\converting lowercase letter to uppercase letters\main.cpp(19): error C2446: '!=' : no conversion from 'const char *' to 'int'
1> There is no context in which this conversion is possible
1>d:\sync files\converting lowercase letter to uppercase letters\converting lowercase letter to uppercase letters\main.cpp(19): error C2040: '!=' : 'int' differs in levels of indirection from 'const char [2]'


Where is the mistake I made? I have exactly copied the code from my book but the problem still exist. Sorry, I cannot find it out. need Help.




Thank you for your attention

Answer
  1. Your while condition should check *sPTR != '\0', "\0" is of type const char*
  2. If toupper is passed a negative value, you invoke UB, so make sure to call it with static_cast<unsigned char> (Details)
  3. You do not need to check islower, toupper already does that
  4. Make your life easier, use std::string:

    void convertToUpper (std::string& str) {
     for (auto& v:str)
         v = toupper(static_cast<unsigned char>(v));
    }