unable to print string while concatenation using toupper() function

Viewed 74

I am facing issues while using toupper() function :
Code :

#include <iostream>
#include <string>
using namespace std;
int main (){
    string input {"ab"};
    string output {""};
    cout << output + toupper(input[0]);
    return 0;
}

the error is :
no operator "+" matches these operands -- operand types are: std::_cx11::string + int .
but if i write :

#include <iostream>
#include <string>
using namespace std;
int main (){
    string input {"ab"};
    string output {""};
    char temp = toupper(input[0]);
    cout << output + temp;
    return 0;
}

it works fine. can anyone tell why ?

1 Answers

toupper's return value is an int, and you can't add an std::string and an int due to no existing operator+(int). Your char temp implicitly converts the int return value to char during its initialization, and since std::string has an operator+(char) overload, this works. Though you can replicate the same behavior with a static_cast instead:

cout << output + static_cast<char>(toupper(input[0]));

As a side note, ctype functions generally a expect value that is representable as unsigned char, or EOF, to be passed, so you should convert char arguments to unsigned char before passing them.

Related