+ 2

Can we insert a variable inside a string? Please help me

Example: Int a,b,sum; Cin>>a>>b; String str("is the result"); Sum=a+b; How we can insert variable(sum) at the beginning of the string?

30th Jan 2020, 7:28 AM
Lukesh Singla
Lukesh Singla - avatar
3 ответов
+ 5
#include <string> #include <iostream> #include <sstream> using namespace std; int main() { int sum, num1, num2; cin >> num1 >> num2; sum = num1 + num2; // using stringstream ostringstream ss; ss << sum << " is the result\n"; string res1 = ss.str(); cout << res1; // alternatively using `to_string` string res2 = to_string(sum) + " is the result\n"; cout << res2; return 0; }
30th Jan 2020, 7:51 AM
Ipang
30th Jan 2020, 7:46 AM
Oma Falk
Oma Falk - avatar
+ 2
I have tried str.insert(0,sum); But it doesn't worked
30th Jan 2020, 7:33 AM
Lukesh Singla
Lukesh Singla - avatar