The following is the problem code.
#include
#include
using namespace std;
void convertToUppercase(char *);
int main()
{
cha
*sPTR != '\0'
, "\0"
is of type const char*
toupper
is passed a negative value, you invoke UB, so make sure to call it with static_cast<unsigned char>
(Details)islower
, toupper
already does thatMake your life easier, use std::string
:
void convertToUpper (std::string& str) {
for (auto& v:str)
v = toupper(static_cast<unsigned char>(v));
}
You are trying to compare a char
to a char const*
(well, really a char const[2]
but that's just a detail). You probably meant to use
while (*sPtr != '\0')
or
while (*sPtr)
Note that your use of islower()
and toupper()
isn't guaranteed to work: the argument to these functions has to be positive but char
may have negative values. You need to first convert the char
to unsigned char
:
toupper(static_cast<unsigned char>(*sPtr))
The test for islower()
isn't needed: on non-lower char
s toupper()
just returns the argument. Omitting the trst is improving the oerformance.
Simple, your comparison is wrong.
while (*sPtr != "\0")
should be
while (*sPtr != '\0')
The condition of your while
loop is wrong, you need to write while(*sPtr != '\0')
with single quotes.
Explanation: '\0'
is a single character, "\0"
is a string constant, i. e. an array of two characters in this case.
There are also shorter ways to write your loop condition:
You can just use a plain zero instead of '\0'
: while(*sPtr != 0)
You can even omit the comparison since you are comparing to zero: while(*sPtr)
Try
while (*sPtr != '\0')
You may also get a seg fault for modifying a string constant
All you need to do is change while (*sPtr != "\0")
to while (*sPtr != '\0')
. You're trying to compare a char to a string. I agree with @chris, though, you don't need to check if it's lower case. It's just messy to do so, and it won't decrease the running time of your algorithm.