C++ Integer Input

Started by
14 comments, last by _goat 17 years, 7 months ago
Thanks EasilyConfused, atoi works great. Now, I am posed with another problem.

Suppose I have:

string str;int num = 10;


I want str to be "The number was 10.\n";

How do I do that. I tried using the + operator between const strings, but it didn't work, I tried usign sprintf() but it did not accept std::string as the first argument. Any help?
--------------------------------------Amaze your friends! Astound your family! Kennify your text!
Advertisement
Personally I'd do this:

std::string int_to_string(int i){    char b[64]; sprintf(b,"%d",i); return b;}void f(){    int n=100;    std::string s="The number is "+int_to_string(n);}


but that is a bit of an old-fashioned hack. I believe you could use an ostringstream to convert the number to a string instead and avoid the potential buffer overflow in my code above.
I got this to work:

std::string itos(int i){    char buffer[64];    itoa(i,buffer,10);    return buffer;}


std::itoa() is not ANSI-defined, but supported by most compilers (according to cplusplus.com).
--------------------------------------Amaze your friends! Astound your family! Kennify your text!
Quote:Original post by Verminox
I got this to work:

std::string itos(int i){    char buffer[64];    itoa(i,buffer,10);    return buffer;}


std::itoa() is not ANSI-defined, but supported by most compilers (according to cplusplus.com).

Why aren't you using std::stringstream?
Quote:Original post by raz0r
Why aren't you using std::stringstream?


Maybe because I don't know how to as yet?

I'll go read up on std::stringstream then.
--------------------------------------Amaze your friends! Astound your family! Kennify your text!
Do it properly:
template <typename T, typename Y> T lexical_cast(const Y& input){    stringstream ss; ss << input;    T t; ss >> t;    return t;}


of course, you'll need to specialise for strings:

template<> lexical_cast<std::string, int>(const int& input){    stringstream ss; ss << input;    return ss.str();}


And if partial specialisation for functions was allowed, well, things'd be so much simpler. Or just include Boost, of course, which is where I stole the idea. In my signature.
[ search: google ][ programming: msdn | boost | opengl ][ languages: nihongo ]

This topic is closed to new replies.

Advertisement