开发者

How to convert from const char* to unsigned int c++

开发者 https://www.devze.com 2023-01-21 20:43 出处:网络
I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck.

I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck. I have a:

const char* charVar;

and i need to convert it to:

unsigned int uintVar;

How can it be done in C++?开发者_如何学运维

Thanks


#include <iostream>
#include <sstream>

const char* value = "1234567";
stringstream strValue;
strValue << value;

unsigned int intValue;
strValue >> intValue;

cout << value << endl;
cout << intValue << endl;

Output:

1234567

1234567


What do you mean by convert?

If you are talking about reading an integer from the text, then you have several options.

Boost lexical cast: http://www.boost.org/doc/libs/1_44_0/libs/conversion/lexical_cast.htm

String stream:

const char* x = "10";
int y;
stringstream s(x);
s >> y;

Or good old C functions atoi() and strtol()


If you really want to convert a pointer to a constant character into an unsigned int then you should use in c++:

const char* p;
unsigned int i = reinterpret_cast<unsigned int>( p );

This converts the address to which the pointer points to into an unsigned integer.

If you want to convert the content to which the pointer points to into an unsigned int you should use:

const char* p;
unsigned int i = static_cast<unsigned int>( *p );

If you want to get an integer from a string, and hence interpret the const char* as a pointer to a const char array, you can use one of the solutions mentioned above.


The C way:

#include <stdlib.h>
int main() {
    const char *charVar = "16";
    unsigned int uintVar = 0;

    uintVar = atoi(charVar);

    return 0;
}

The C++ way:

#include <sstream>
int main() {
    istringstream myStream("16");
    unsigned int uintVar = 0;

    myStream >> uintVar;

    return 0;
}

Notice that in neither case did I check the return code of the conversion to make sure it actually worked.


In C this can be done using atoi which is also available to C++ via cstdlib.


I usually use this generic function to convert a string into "anything":

  #include <sstream>
  // Convert string values into type T results.
  // Returns false in case the conversion fails.
  template <typename T>
  bool getValueFromString( const std::string & value, T & result )
  {
    std::istringstream iss( value );
    return !( iss >> result ).fail();
  }

just use it as in:

int main()
{
  const char * a_string = "44";
  unsigned int an_int;
  bool         success;

  // convert from const char * into unsigned int
  success = getValueFromString( a_string, an_int );


  // or any other generic convertion
  double       a;
  int          b;
  float        c;
  // conver to into double
  success = getValueFromString( "45", a );

  // conve rto into int
  success = getValueFromString( "46", b );

  // conver to into float
  success = getValueFromString( "47.8", c );
}


atoi function will convert const char* to int, which can be implicitly converted to unsigned. This won't work for large integers that don't fit in int.

A more C++-ish way is to use strings and streams

#include <sstream>
#include <string>

int main()
{
   std::string strVar;
   unsigned uintVar;
   std::istringstream in(strVar);
   in >> uintVar;
}

An easier but nonstandard way would be to use boost's lexical cast.

HTH


So I know this is old but thought I would provide a more efficient way of doing this that will give you some flexibility on what you want as a base is.

#include<iostream>

unsigned long cstring_to_ul(const char* str, char** end = nullptr, int base = 10)
{
    errno = 0; // Used to see if there was success or failure

    auto ul = strtoul(str, end, base);

    if(errno != ERANGE)
    {
       return ul;
    }

    return ULONG_MAX;
}

What this will do is create a wrapper around the method strtoul(const char* nptr, char** endptr, int base) method from C. For more information on this function you can read the description from the man page here https://linux.die.net/man/3/strtoul

Upon failure you will have errno = ERANGE, which will allow you to do a check after calling this function along with the value being ULONG_MAX.

An example of using this can be as follows:

int main()
{
    unsigned long ul = cstring_to_ul("3284201");

    if(errno == ERANGE && ul == ULONG_MAX)
    {
        std::cout << "Input out of range of unsigned long.\n";
        exit(EXIT_FAILURE);
    }

    std::cout << "Output: " << ul << "\n";
 }

This will give the output

Output: 3284201


Try in this way

#include<iostream>
#include <typeinfo>             //includes typeid

using namespace std;

int main(){

char a  = '3';
int k = 3;

const char* ptr = &a;

cout << typeid(*ptr).name() << endl;                    //prints the data type c = char
cout << typeid(*ptr-'0').name() << endl;                //prints the data type i = integer

cout << *ptr-'0' << endl;

return 0;
}


Without more information there is no way to properly answer this question. What are you trying to convert exactly? If charVar is an ascii representation of the string, then you can do like others have suggested and use stringstreams, atoi, sscanf, etc.

If you want the actual value pointed to by charVar, then instead you'd want something like:

intValue = (unsigned int)(*charVal);

Or if charVal is the pointer to the first byte of an unsigned integer then:

intValue = *((unsigned int*)(charVal));


const char* charVar = "12345";
unsigned int uintVar;
try {
  uintVar = std::stoi( std::string(charVar) );
}
catch(const std::invalid_argument& e) {
  std::cout << "Invalid Arg: " << e.what() << endl;
}
catch(const std::out_of_range& e) {
  std::cout << "Out of range: " << e.what() << endl;
}


You can also use strtoul or _tcstoul to get unsigned long value from const char* and then cast the value to unsigned int.

http://msdn.microsoft.com/en-us/library/5k9xb7x1(v=vs.71).aspx


const char* charVar = "1864056953";
unsigned int uintVar = 0;

for (const char* it = charVar; *it != 0; *it++){

    if ((*it < 48) || (*it > 57)) break;            // see ASCII table

    uintVar *= 10;                                  // overflow may occur
    uintVar += *it - 48;                            // 
}

std::cout << uintVar << std::endl;
std::cout << charVar << std::endl;
0

精彩评论

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