tags:

views:

108

answers:

4

Hi,

Is it recommended to use cstdio,cstring,cmath in c++? I was writing a program that needed pow , strlen and sprintf ... for that the only way I could do it was to include these 3 headers. Is there a better C++ way to do it?

Thanks

+5  A: 

That is the correct way.

Dirk Eddelbuettel
Not sure I agree with this :) It sounds like he's dealing with C-style strings, not C++ strings. The question I would have is: should he not be using std::basic_string<T> instead of NULL terminated strings along with the IO manipulation features of C++ instead of sprintf? cheers :)
OJ
+10  A: 

You can use std::stringstream instead of sprintf and std::string instead of C-style strings. But C++ just uses the C library for math functions.

dan04
There's a lot of useful stuff besides sprintf in string.h
kotlinski
But it's all for using char* strings. If you switch to C++'s string class you get it all in the string header. (O.K., sometimes you might need algorithm as well)And it's preferred to use C++'s string than a char* if possible.
Shiroko
string.h has some non-string functions too like memcpy and memset.
dan04
memcpy and memset are superceded by std::copy and std::fill. For POD types, the GNU implementation falls through to memcpy. Not sure about memset.
Potatoswatter
+3  A: 

For math functions, <cmath> is the correct way; however, for I/O, you should be using <iostream>, <sstream>, <fstream>, and friends. For string manipulation, <string> is the way to go.

Michael Aaron Safyan
iostream is much slower than scanf/printf (acm olympiads experience)
osgx
@osgx, not sure I buy that. scanf/printf have to deal with a lot more formatting than iostreams does. Which implementation did you use? Any reasonable implementation of iostream should be at least as fast.
Michael Aaron Safyan
@Michael Aaron Safyan, on our olymp problem was with `sync_with_stdio`. libstdc++'s iostream from gcc has this enabled in Linux. After turning this off speed of iostream increased
osgx
+1  A: 

cmath isn't really superseded in C++, since there's really nothing to make them better. However, stringstreams/iostreams are far far superior to the cstring and cstdio lot.

If you have a C string, you can convert to a std::string quite easily, and the same for back again. If you're using strings, ALWAYS use the C++ string libraries over strlen, sprintf, and that.

DeadMG