convert pointer string to integer

后端 未结 3 536
不思量自难忘°
不思量自难忘° 2021-01-24 23:37

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

相关标签:
3条回答
  • 2021-01-25 00:20
    #include <sstream>
    
    // ...
    
    string str(*(treePtr->item.getInvest())); // assuming getInvest() returns ptr
    istringstream ss(str);
    int the_number;
    ss >> the_number;
    
    0 讨论(0)
  • 2021-01-25 00:25

    if you have access to boost:

    int number= boost::lexical_cast<int>(treePtr->item.getInvest());
    
    0 讨论(0)
  • 2021-01-25 00:28

    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).

    0 讨论(0)
提交回复
热议问题