Reputation: 97
I have a string 039
and i have this following code
cout<<str2[1]+str2[0]+str2[2]<<endl;
I expect this to give me 309
,but it gives me 156
.How is that considering that separately all they give me 3 0 9
?
Upvotes: 0
Views: 88
Reputation: 15521
It is because you are summing the characters / their underlying integral values together. If you want to output the characters themselves use the <<
operator, not the +
. The characters and their underlying values are (assuming ASCII):
'3' 51
'0' 48
'9' 57
The expression of:
str2[1] + str2[0] + str2[2]
sums the characters together, it does not send them to standard output one by one, so the expression becomes:
51 + 48 + 57
resulting in 156
. Use the operator<< instead:
#include <iostream>
#include <string>
int main() {
std::string str2 = "039";
std::cout << str2[1] << str2[0] << str2[2] << '\n';
}
As pointed out in the comments, character types are integral types and your char
type probably covers the range from -127
to 127
. This also assumes you are using ASCII encoding which maps the characters to values given above.
Upvotes: 6
Reputation: 76
If you need retrieve result as a string use ostringstream
:
#include <sstream>
std::ostringstream stream;
stream << str2[1] << str2[0]<< str2[2];
std::string res = stream.str();
std::cout <<"> " << res << std::endl;
Upvotes: 0
Reputation: 642
If str2[1] is char, then:
Char is just like int, but from -127 to 127(or 0 to 255). See ASCII codes.
Then if you do str2[1]+str2[0]+str2[2]
, you will get some ASCII code.
In c++ you can't do char+char and get 2 chars
.
Do this:
cout<<str2[1]<<str2[0]<<str2[2]<<endl;
Upvotes: 1