473,396 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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
Jul 22 '05 #1
3 14770
> 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
Jul 22 '05 #2
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-lit....html#faq-38.1
http://www.parashift.com/c++-faq-lite/input-output.html

Jul 22 '05 #3
walle
1
Yes stringstreams are still terribly slow (at least on gcc).
Did a little benchmark comparing strtod and ostringstream.

Again if you can live with the overhead, it is the cleanest way to do string conversions (I use streams a lot but on some places going back to oldschool C-style atoi, strtod etc. is necessary)

This is copied from my page stringstream benchtest


Here follows a simple example (okay did not try to optimize anything here,
just used sstream in a classroom type example and compared it to the c-style
sprintf and strtod functions).

What we notice is :
1. The cstreams implementation is almost 5 times faster than cppstreams
2. The cppstreams gives an extra double which differs from original
after conversion to string and back. The differences between value and repVal are normal/understandable but it's not logical why the cpp stringstreams have one more difference between value/repVal than when using srtod+sprintf...

Here are my files and a testrun:


wschrep@pascal:~/cpp-work/streambench.cpp> ls

cppstreams.cpp cppstreams.out cstreams.cpp cstreams.out Makefile

wschrep@pascal:~/cpp-work/streambench.cpp> cat cppstreams.cpp

#include <iostream>

#include <sstream>



using namespace std;



int main(){

double value = 1.0;

double repVal= 0;

for( int i=0;i<100000;i++){

value = (value/2)+1;



//double to string

ostringstream os;

os << value << endl;

string strVal = os.str();



//string to double

istringstream is( strVal );

is >> repVal;

if( repVal != value ){

cout << "repVal = "<<repVal<<" != value =" << value <<endl;

}

}

cout << "done!"<<endl;

return 0;

}



wschrep@pascal:~/cpp-work/streambench.cpp> cat cstreams.cpp

#include <iostream>

#include <sstream>

using namespace std;

#include <stdio.h>

#include <stdlib.h>



int main(){

double value = 1.0;

double repVal= 0;



for( int i=0;i<100000;i++){

value = (value/2)+1;



//double to string

char cp[255];

sprintf( cp, "%f", value );

string strVal( cp );



//string to double

char * pEnd;

repVal = strtod( strVal.c_str(), &pEnd );

if( repVal != value ){

cout << "repVal = "<<repVal<<" != value =" << value <<endl;

}

}

cout << "done!"<<endl;

return 0;

}



wschrep@pascal:~/cpp-work/streambench.cpp> cat Makefile

INCLUDE = -I.

CXX = g++

CXXFLAGS = -O2 -Wall $(INCLUDE)



all: cppstreams cstreams



cppstreams: cppstreams.o

$(CXX) $(CXXFLAGS) -o cppstreams cppstreams.o



cstreams: cstreams.o

$(CXX) $(CXXFLAGS) -o cstreams cstreams.o

clean:

@rm -vf *.o *~ DEADJOE cppstreams cstreams



wschrep@pascal:~/cpp-work/streambench.cpp> make

g++ -O2 -Wall -I. -c -o cppstreams.o cppstreams.cpp

g++ -O2 -Wall -I. -o cppstreams cppstreams.o

g++ -O2 -Wall -I. -c -o cstreams.o cstreams.cpp

g++ -O2 -Wall -I. -o cstreams cstreams.o

wschrep@pascal:~/cpp-work/streambench.cpp> time ./cppstreams > cppstreams.out



real 0m1.558s

user 0m1.557s

sys 0m0.001s

wschrep@pascal:~/cpp-work/streambench.cpp> time ./cstreams > cstreams.out



real 0m0.334s

user 0m0.331s

sys 0m0.002s

wschrep@pascal:~/cpp-work/streambench.cpp> diff cstreams.out cppstreams.out

0a1

> repVal = 1.98438 != value =1.98438



So wassup here dudes? Don't have time to find a mailing list to post this so I'm just gonna put it here in my DIY blog

Incidently I was benching these 2 methods of conversion for my matrix class which will have to do such conversions from string to double and other types when parsing scripts and interpreting them...
For now I'm probably going to write a little wrapper class around the c-style conversion I guess... since it gives such a speed improvement
Jul 4 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Christopher Benson-Manica | last post by:
What is the preferred C++ alternative to C's atoi(), if there is one? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to...
5
by: William Payne | last post by:
How do you get rid the contents in a std::stringstream? I'm using one in a for loop to format some status messages which I print to the screen. The stringstream member function clear() only clears...
2
by: Sona | last post by:
Hi, I have a char* that holds an ascii character in its first element (at least I think that's what it holds because when I print it, it prints weird characters). I need to convert this into an...
4
by: Sharon | last post by:
hi all what are the reverse functions of atof( ), atoi( ) and atol( ) ? I want to change sth to string thx!
11
by: rayw | last post by:
I'm pretty new to C, although I did do some years ago now. I've been told that itoa is no longer a standard function, and that the ato... functions - although in the std - are not recommended. ...
0
by: sundman.anders | last post by:
Hi all! I have a question about thread synchronization and c++ streams (iostreams, stringstreams, etc). When optimizing a program for a multicore processor I found that stringstream was causing...
4
by: Ram | last post by:
Hi All, Firstly i am a newbie and trying to learn C. The background of the problem is Program: Presently I am working on a program of numerology and the I/P will be the name and output...
4
by: Johannes Bauer | last post by:
Hello group, I've a simple problem with the precision specifiers of stringstream. Let's say I have this: double x = 123.4567890; std::stringstream Strm; Strm.precision(4); Strm <<...
50
by: Bill Cunningham | last post by:
I have just read atoi() returns no errors. It returns an int though and the value of the int is supposed to be the value of the conversion. It seems to me that right there tells you if there was...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.