-6

I'm using c_str(), atoi and atof functions for converting string variables to integer or float/double. For example,

val = atoi(val1.c_str());   
val = atof(val1.c_str());

So, I would like to know if I need to include and . Thanks.

NirMH
  • 4,769
  • 3
  • 44
  • 69
  • 4
    `atoi` and friends are in `stdlib.h`. `c_str()` is a member function of `std::string`, which is in the `string` header. You can get that information yourself by searching here: http://en.cppreference.com/w/ – juanchopanza Jul 06 '14 at 08:33
  • There are two possibilities: Try to included the suspects until the compiler warning changes or read the descriptions as juanchopanza referred. – harper Jul 06 '14 at 08:38
  • Downvoters gonna downvote. – Korchkidu Jul 06 '14 at 08:45
  • @harper Your first suggestion is not great because you can end up with a non-portable solution (e.g. by including a header that includes one of the headers you actually need.) – juanchopanza Jul 06 '14 at 08:50
  • 1
    This question appears to be off-topic because it asks about a C++ reference. Finding out in which header a function lives can be easily done with a minimal research effort. Moreover, it doesn't add value to Stackoverflow. – danijar Jul 06 '14 at 08:59
  • 1
    You should avoid `atoi` and friends, because they will give you the same result (0) for the two strings `"0"` and `"xxx"`, which makes error handling almost impossible. – Christian Hackl Jul 06 '14 at 11:37

1 Answers1

2

None of those require the header <cstring>. The function c_str() requires <string> and including <cstdlib> (the C++ version of the <stdlib.h> header) guarantees you have std::atoi and std::atof.

Also, the site cplusplus.com is not necessarily the best reference, you should probably use cppreference.com

Spearman
  • 149
  • 6
  • 1
    Almost: `atoi` and `atof` are not guaranteed to be in `cstdlib`. What is guaranteed is that you get `std::atoi` and `std::atof`. Both `atoi` and `atof` are guaranteed to be in `stdlib.h`. – juanchopanza Jul 06 '14 at 08:48
  • @juanchopanza Both? Surely you mean just the non-`std` versions. – Joseph Mansfield Jul 06 '14 at 08:51
  • @JosephMansfield I meant both `atoi` and `atof`. Edited the comment. – juanchopanza Jul 06 '14 at 08:51
  • Is there a special reason to choose [cppreference.com](http://cppreference.com) over [cplusplus.com](http://cplusplus.com)? – danijar Jul 06 '14 at 08:55
  • Here is a discussion http://stackoverflow.com/questions/6520052/whats-wrong-with-cplusplus-com cppreference.com is also a wiki – Spearman Jul 06 '14 at 09:11
  • per [cppreference](http://en.cppreference.com/w/cpp/string/basic_string/c_str) and a test on a MAC is the correct include. – MikeF Sep 15 '17 at 00:58