+ 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?
3 Answers
+ 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;
}
+ 2
I have tried
str.insert(0,sum);
But it doesn't worked