Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it recommended to use cstdio, cstring, cmath, etc. in C++?

Tags:

c++

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

like image 965
user855 Avatar asked Mar 21 '10 22:03

user855


4 Answers

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.

C++ adds some convenient overloads for math functions (e.g. you can use exp() for float.) They are available in <math.h> not only in <cmath> though.

like image 118
dan04 Avatar answered Nov 01 '22 04:11

dan04


That is the correct way.

like image 43
Dirk Eddelbuettel Avatar answered Nov 01 '22 03:11

Dirk Eddelbuettel


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.

like image 3
Michael Aaron Safyan Avatar answered Nov 01 '22 02:11

Michael Aaron Safyan


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.

like image 1
Puppy Avatar answered Nov 01 '22 03:11

Puppy