Jump to content
  • Advertisement
Sign in to follow this  
neverland

convert between int and std::string

This topic is 4810 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all Is there any function in standard C++ that converts between int and std::string itoa() and atoi() use char*, I need the function that uses std::string as argument NOT the C-style string. thanks in advance

Share this post


Link to post
Share on other sites
Advertisement

//to string
std::ostringstream oss;
oss<<myInt;
std::string myStr = oss.str();

//from string
std::stringstream ss;
ss<<myStr;
int myInt;
if(!(ss>>myInt)) {
throw new std::bad_cast();
}

Share this post


Link to post
Share on other sites
Even though Washu has given you the correct answer, you do know that you can use the c_str() member of the std::string class to use those functions, correct?

// string to int
std::string str = "25";
int value = atoi( str.c_str() );
If you are using standard C++ though, it's more often better to use their functions and classes, the ones Washu has shown, but just making sure you do know std::string is compatible with char* [wink].

Share this post


Link to post
Share on other sites
Quote:
Original post by Washu

//to string
std::ostringstream oss;
oss<<myInt;
std::string myStr = oss.str();


I used your method, but it did not compile.
#include <iostream>
#include <string>
using namespace std;

int main()
{
ostringstream oss;
int i = 2000;
oss << i;
string str = oss.str();
cout << str << endl;
}


Share this post


Link to post
Share on other sites
Of course not, because you didn't look up the header that ostringstream resides in and include it. Just one of the many hazards of copy and pasting code...

Share this post


Link to post
Share on other sites
Quote:
Original post by neverland
I used your method, but it did not compile.
*** Source Snippet Removed ***


You have to include sstream too. So your code should be

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
ostringstream oss;
int i = 2000;
oss << i;
string str = oss.str();
cout << str << endl;
}



A tip is to read what messages you get when compiling next time. It would have told you what was wrong, though it may be a bit cryptic.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!