1

I am trying to convert treePtr->item.getInvest() which contains a string to an integer. Is this possible?

jleahy
  • 16,149
  • 6
  • 47
  • 66
D-Boy
  • 13
  • 1
  • 3

3 Answers3

8

if you have access to boost:

int number= boost::lexical_cast<int>(treePtr->item.getInvest());
Gustavo Muenz
  • 9,278
  • 7
  • 40
  • 42
6
#include <sstream>

// ...

string str(*(treePtr->item.getInvest())); // assuming getInvest() returns ptr
istringstream ss(str);
int the_number;
ss >> the_number;
wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
  • It works, but it is inefficient - there's at least one heap allocation and free there, which may well get stuck in a mutex if your program in multi-threaded. Are you doing this once, or millions of times? – alex tingle Nov 01 '09 at 02:57
  • wilhelmtell: Just because we are writing C++ does not mean that everything has to be a class. Premature optimisation may be the root of all evil, but wilfully choosing to do extra work is perverse. – alex tingle Nov 01 '09 at 11:37
4

Better to use strtol() than mess around with streams.

const char* s = treePtr->item.getInvest();
const char* pos;
long the_number = ::strtol(s,&pos,10);
if(pos!=s)
    // the_number is valid

strtol() is a better choice because it gives you an indication of whether number returned is valid or not. Furthermore it avoids allocating on the heap, so it will perform better. If you just want a number, and you are happy to accept a zero instead of an error, then just use atol() (which is just a thin wrapper around strtol that returns zero on error).

alex tingle
  • 6,920
  • 3
  • 25
  • 29
  • 2
    "Better to use strtol" ... why? – Drew Dormann Nov 01 '09 at 00:30
  • 1
    Streams are "the C++ way." I prefer it to worrying about getting all the details associated with C strings right. – mch Nov 01 '09 at 00:35
  • Shmoopty: fair question. I have added my reasoning to the answer. – alex tingle Nov 01 '09 at 02:51
  • mch: Streams certainly have their place, but a straight replacement for `strtol()` is not one of them. Just as you would not use a `std::string` when a `const char*` would suffice. – alex tingle Nov 01 '09 at 02:54
  • 1
    +1 for this answer. streams have their place but are very inefficient. you could do a template specialization for boost::lexical_cast that uses strtol – m-sharp Nov 01 '09 at 04:10
  • but it is sometimes best to get amature developers to use strings and functions that avoid seg faults from incorrect array sizes and access when using char*'s. I find that char* issues are a large percentage of the bugs in peoples code unless they are good, careful programmers – Fuzz Nov 01 '09 at 04:17
  • @alex tingle streams do have error states, and stringstreams use them when a parse fails. – wilhelmtell Nov 01 '09 at 04:31