Can someone explain why this short code in C++ doesn't produce the expected output. The code is supposed to print the string in capital letters.
#include <iostream>
#include <string>
using namespace std;
int main(){
string sample("hi, i like cats and dogs.");
cout << "small: " << sample << endl << "BIG : ";
for(char c: sample)
cout << toupper(c);
cout<<endl;
return 0;
}
The output of the above program is:
small: hi, i like cats and dogs.
BIG : 72734432733276737569326765848332657868326879718346
but I expected:
small: hi, i like cats and dogs.
BIG : HI, I LIKE CATS AND DOGS.
I've only programmed in python.
toupper
returnsint
. You need to cast the return value tochar
such that the output stream operator<<
prints out the character and not its numeric value.You should also cast the input to
unsigned char
, to cover the case wherechar
is signed and your character set includes negative numbers (this would invoke undefined behaviour intoupper
). For example,Note that you need to include the relevant header (
cctype
if you wantstd::toupper
orctype.h
if you want C'stoupper
.)