| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"Mike Chirico" |
| Date: |
19 Nov 2003 08:18:52 AM |
| Object: |
atoi: stringstream or old C sprintf function |
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
.
|
|
| User: "Peter van Merkerk" |
|
| Title: Re: stringstream or old C sprintf function |
19 Nov 2003 08:43:00 AM |
|
|
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());.
--
Peter van Merkerk
peter.van.merkerk(at)dse.nl
.
|
|
|
|
| User: "Grumble" |
|
| Title: Re: atoi: stringstream or old C sprintf function |
19 Nov 2003 09:59:06 AM |
|
|
Mike Chirico wrote:
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?
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-38.1
http://www.parashift.com/c++-faq-lite/input-output.html
.
|
|
|
|

|
Related Articles |
|
|