for loop c++ 'toupper' implementation -


can explain why short code in c++ doesn't produce expected output. code supposed print string in capital letters.

#include <iostream> #include <string> using namespace std;  int main(){     string sample("hi, cats , dogs.");     cout << "small: " << sample << endl << "big  : ";      for(char c: sample)         cout << toupper(c);     cout<<endl;  return 0; } 

the output of above program is:

small: hi, cats , dogs. big  : 72734432733276737569326765848332657868326879718346 

but expected:

small: hi, cats , dogs. big  : hi, cats , dogs. 

i've programmed in python.

toupper returns int. need cast return value char such output stream operator << prints out character , not numeric value.

you should cast input unsigned char, cover case char signed , character set includes negative numbers (this invoke undefined behaviour in toupper). example,

cout << static_cast<char>(toupper(static_cast<unsigned char>(c))); 

note need include relevant header (cctype if want std::toupper or ctype.h if want c's toupper.)


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -