Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

c++ - How can integer be appended to string if + '0' is provided

I encountered with a strange code in a solution of a programming problem and I couldn't find any good idea about it. Here,

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main() {
    int count=8;
    string temp="Hello ";
    temp+=count+'0';
    cout<<temp;
    return 0;
}
Output is: Hello 8

integer variable count was appended to the string even without type casting the integer variable. I guess it worked because of '0' but what is this process or method.

question from:https://stackoverflow.com/questions/65645046/how-can-integer-be-appended-to-string-if-0-is-provided

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

integer variable count was appended to the string even without type casting the integer variable.

No, no integer variable was appended. The only suitable overload for the += operator is the one that takes a single char parameter, and ends up adding a single character to the string. The integer value type gets converted to a char type, and the rest is history.

So, adding 8 to the character '0' produces, unsurprisingly, character '8'. Things, of course, go in an exciting direction if your integer variable is negative, or greater than 9. You should try it, the results should be illuminating.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...