开发者

which is preferd use istrstream or strtol/strtod for reading number from string

I have to read number from string .which one is safe and preferred

  1. istrstream
  2. atoi/atof
  3. strtol/strto

Please guide 开发者_StackOverflow中文版me.


I have used all of these but don't know which is preferable. I did however find a decent article (here) on the pros and cons between the last two which is well worth a read


The functions atoi/atof/strtol all have more or less cumbersome and non-obvious error checking involving errno (strtol is way much better than atoi in any case, so avoid using atoi). See theese answers for some discussion. I do not know C++ very well, so I cannot comment on istrstream.


Definitely not #1. strstreams are deprecated in C++ and have lots of problems in their use. You want their replacement, - the stringstream classes declared in <sstream>. These are the best general-purpose solution to your problem - they are type-safe and easy to use.


Why use <iostream> instead of <cstdio> ?

Increase type safety, reduce errors, allow extensibility, and provide inheritability.

printf() is arguably not broken, and scanf() is perhaps livable despite being error prone, however both are limited with respect to what C++ I/O can do. C++ I/O (using << and >>) is, relative to C (using printf() and scanf()):

  • More type-safe: With <iostream>, the type of object being I/O'd is known statically by the compiler. In contrast, <cstdio> uses "%" fields to figure out the types dynamically.

  • Less error prone: With <iostream>, there are no redundant "%" tokens that have to be consistent with the actual objects being I/O'd. Removing redundancy removes a class of errors.

  • Extensible: The C++ <iostream> mechanism allows new user-defined types to be I/O'd without breaking existing code. Imagine the chaos if everyone was simultaneously adding new incompatible "%" fields to printf() and scanf()?!

  • Inheritable: The C++ <iostream> mechanism is built from real classes such as std::ostream and std::istream. Unlike <cstdio>'s FILE*, these are real classes and hence inheritable. This means you can have other user-defined things that look and act like streams, yet that do whatever strange and wonderful things you want. You automatically get to use the zillions of lines of I/O code written by users you don't even know, and they don't need to know about your "extended stream" class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜