如何将const char*转换为unsigned int c++

时间:2021-07-08 05:37:53

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:

我是c++编程的新手,我一直在尝试将const char*转换为无符号int。我有一个:

const char* charVar;

and i need to convert it to:

我需要把它转换成:

unsigned int uintVar;

How can it be done in C++?

如何在c++中实现呢?

Thanks

谢谢

12 个解决方案

#1


33  

#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

1234567

1234567

#2


25  

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

提高词汇演员: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()

或良好的旧C函数atoi()和strtol()

#3


14  

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

如果您真的想要将指针转换为常量字符,那么您应该使用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:

如果您想将指针指向的内容转换为无符号int类型,您应该使用:

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.

如果您想从字符串中获得一个整数,因此将const char*解释为一个指向const char数组的指针,那么您可以使用上面提到的解决方案之一。

#4


6  

The C way:

C:

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

    uintVar = atoi(charVar);

    return 0;
}

The C++ way:

c++道:

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

注意,在这两种情况下,我都没有检查转换的返回代码,以确保它实际工作。

#5


5  

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

在C语言中,这可以通过atoi来实现,atoi也可以通过cstdlib来实现。

#6


2  

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.

atoi函数将const char*转换为int,可以隐式地转换为unsigned。对于不适合int的大整数,这是行不通的。

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

更接近c++的方法是使用字符串和流

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

一个简单但不标准的方法是使用boost的词汇转换。

HTH

HTH

#7


2  

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 );
}

#8


1  

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.

没有更多的信息,就没有办法正确地回答这个问题。你到底想转换什么?如果charVar是字符串的ascii表示形式,那么您可以像其他人建议的那样使用stringstreams、atoi、sscanf等。

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:

或者如果charVal是一个无符号整数的第一个字节的指针,则:

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

#9


1  

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;
}

#10


1  

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

您还可以使用strtoul或_tcstoul从const char*获取无符号长值,然后将值转换为无符号int。

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

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

#11


1  

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;

#12


1  

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

这将做的是,在方法strtoul(const char* nptr, char** endptr, int base)方法中创建一个包装器,以获得更多关于这个函数的信息,您可以从这里的man页面读取描述。

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.

在失败时,您将拥有errno = ERANGE,这将允许您在调用此函数后进行检查,并将其值设置为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

输出:3284201

#1


33  

#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

1234567

1234567

#2


25  

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

提高词汇演员: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()

或良好的旧C函数atoi()和strtol()

#3


14  

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

如果您真的想要将指针转换为常量字符,那么您应该使用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:

如果您想将指针指向的内容转换为无符号int类型,您应该使用:

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.

如果您想从字符串中获得一个整数,因此将const char*解释为一个指向const char数组的指针,那么您可以使用上面提到的解决方案之一。

#4


6  

The C way:

C:

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

    uintVar = atoi(charVar);

    return 0;
}

The C++ way:

c++道:

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

注意,在这两种情况下,我都没有检查转换的返回代码,以确保它实际工作。

#5


5  

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

在C语言中,这可以通过atoi来实现,atoi也可以通过cstdlib来实现。

#6


2  

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.

atoi函数将const char*转换为int,可以隐式地转换为unsigned。对于不适合int的大整数,这是行不通的。

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

更接近c++的方法是使用字符串和流

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

一个简单但不标准的方法是使用boost的词汇转换。

HTH

HTH

#7


2  

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 );
}

#8


1  

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.

没有更多的信息,就没有办法正确地回答这个问题。你到底想转换什么?如果charVar是字符串的ascii表示形式,那么您可以像其他人建议的那样使用stringstreams、atoi、sscanf等。

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:

或者如果charVal是一个无符号整数的第一个字节的指针,则:

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

#9


1  

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;
}

#10


1  

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

您还可以使用strtoul或_tcstoul从const char*获取无符号长值,然后将值转换为无符号int。

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

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

#11


1  

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;

#12


1  

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

这将做的是,在方法strtoul(const char* nptr, char** endptr, int base)方法中创建一个包装器,以获得更多关于这个函数的信息,您可以从这里的man页面读取描述。

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.

在失败时,您将拥有errno = ERANGE,这将允许您在调用此函数后进行检查,并将其值设置为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

输出:3284201