string help

I want to convert an int to a string and put it into the middle of a existing string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

string strr = "abc"; // strr hold abc. I want to put the string inside str in between a and b
//the answer should be a10bc


for(int i = 1;i < 2;i++)
{
             //code goes here
         
        }
        cout << strr;
        
    system("pause");
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
    const int a = 10 ;
    const std::string str = "abc" ;

    const std::string strr = str.empty() ? std::to_string(a) :
                                           str.front() + std::to_string(a) + str.substr(1) ;
    std::cout << str << ' ' << strr << '\n' ;
}

http://coliru.stacked-crooked.com/a/41dfa16fb82071d0
JLBorges I actually used insert()

Can you give me a good up to date c++ IDE and compiler?
My current IDE can't do to_string()
It's unlikely your compiler can't do to_string.
You probably just have to set it to use C++11.
On gcc you just add the -std=c++11 option.
Look for a place to add compiler options (or possibly just a checkbox).
> Can you give me a good up to date c++ IDE and compiler?

If you are on Windows, go for Visual Studio 2017 Community Edition.
https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community&rel=15
In the installer, select 'Desktop Development with C++'


> My current IDE can't do to_string()

As a temporary fix, try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <sstream>

namespace utility
{
    std::string to_string( int v )
    {
        std::ostringstream stm ;
        stm << v ;
        return stm.str() ;
    }
}

int main()
{
    const int a = 10 ;
    const std::string str = "abc" ;

    const std::string strr = str.empty() ? utility::to_string(a) :
                                           str[0] + utility::to_string(a) + str.substr(1) ;
    std::cout << str << ' ' << strr << '\n' ;
}
Topic archived. No new replies allowed.