atoi: stringstream or old C sprintf function

M

Mike Chirico

Sorry about the newbie question. What's the best way to convert
numbers to strings in C++. The following works, but is it better than
using the sprintf() "old C" way of converting?


#include <iostream>
#include <string>
#include <sstream>
#include <list>

using namespace std;
int main(void)
{
list<string> ml;
string s;
stringstream ss;



for(int i=0; i < 3000; ++i)
{
ss << "sample text " << i ;
ml.push_front( ss.str() );
ss.str("");
}

cout << ml.front() << endl;
}


What about the fact that the stringstream has to be cleared
ss.str("")...does that incur additional overhead? Maybe there is a
better way?


Regards,


Mike Chirico
 
P

Peter van Merkerk

Sorry about the newbie question. What's the best way to convert
numbers to strings in C++. The following works, but is it better than
using the sprintf() "old C" way of converting?


#include <iostream>
#include <string>
#include <sstream>
#include <list>

using namespace std;
int main(void)
{
list<string> ml;
string s;
stringstream ss;

for(int i=0; i < 3000; ++i)
{
ss << "sample text " << i ;
ml.push_front( ss.str() );
ss.str("");
}

cout << ml.front() << endl;
}


What about the fact that the stringstream has to be cleared
ss.str("")...does that incur additional overhead? Maybe there is a
better way?

Is your program too slow? If yes, is it caused by stringstream? If the
answer is no to either of these questions, then why worry about the
overhead? Unless the stringstream introduces an unacceptable perfomance
problem in your program, I'd say stick with what you have got; it looks
pretty good to me!

Since ss is only used inside the loop, you might consider moving the
"stringstream ss;" line inside loop and remove the "ss.str("");" line.
It is a little bit cleaner, though it is probably also slightly slower
(but I doubt you'd be able to measure the difference).

The std::stringstream solution is not necessarilly the fastest solution,
but it is clean and safe unlike the C way of converting. The overhead of
ss.str("") is probably very small compared to the cost of doing
ml.push_front(ss.str());.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top