No conversion from “const char” to “int”

前端 未结 6 1150
野性不改
野性不改 2021-01-25 11:01

The following is the problem code.

#include 
#include 
using namespace std;

void convertToUppercase(char *);

int main()
{
    cha         


        
相关标签:
6条回答
  • 2021-01-25 11:22
    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));
      }
      
    0 讨论(0)
  • 2021-01-25 11:29

    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 chars toupper() just returns the argument. Omitting the trst is improving the oerformance.

    0 讨论(0)
  • 2021-01-25 11:30

    Simple, your comparison is wrong.

    while (*sPtr != "\0")
    

    should be

    while (*sPtr != '\0')
    
    0 讨论(0)
  • 2021-01-25 11:30

    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:

    1. You can just use a plain zero instead of '\0': while(*sPtr != 0)

    2. You can even omit the comparison since you are comparing to zero: while(*sPtr)

    0 讨论(0)
  • 2021-01-25 11:31

    Try

    while (*sPtr != '\0')
    

    You may also get a seg fault for modifying a string constant

    0 讨论(0)
  • 2021-01-25 11:46

    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.

    0 讨论(0)
提交回复
热议问题