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

Biz*_*woo 14 c++

我是c ++编程的新手,我一直试图从const char*转换为unsigned int而没有运气.我有一个:

const char* charVar;
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为:

unsigned int uintVar;
Run Code Online (Sandbox Code Playgroud)

如何在C++中完成?

谢谢

Ste*_*end 37

#include <iostream>
#include <sstream>

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

unsigned int intValue;
strValue >> intValue;

cout << value << endl;
cout << intValue << endl;
Run Code Online (Sandbox Code Playgroud)

输出:

1234567

1234567

  • 这个答案不涉及转换,并且它带来了一堆 C++ 不一定需要的复杂功能。理想情况下,您会弄清楚如何完全不使用 stl 或模板。引入这些功能会大大增加编译时间。当我将小型 xml 解析器中大部分对 stl 的引用去掉后,编译时间从 30 秒缩短到不到一秒。这就是为什么大型项目最终需要一个小时来编译,除非你家里有 64 核 cpu。 (2认同)

Let*_*_Be 25

你是什​​么意思转换?

如果您正在谈论从文本中读取整数,那么您有几个选项.

提升词汇演员:http://www.boost.org/doc/libs/1_44_0/libs/conversion/lexical_cast.htm

字符串流:

const char* x = "10";
int y;
stringstream s(x);
s >> y;
Run Code Online (Sandbox Code Playgroud)

或旧的C功能atoi()strtol()

  • ...虽然我现在想要将其移除以进行CRT迎合:-) (2认同)

ogn*_*i42 15

如果你真的想将指向常量字符的指针转换为unsigned int,那么你应该在c ++中使用:

const char* p;
unsigned int i = reinterpret_cast<unsigned int>( p );
Run Code Online (Sandbox Code Playgroud)

这会将指针指向的地址转换为无符号整数.

如果要将指针指向的内容转换为unsigned int,则应使用:

const char* p;
unsigned int i = static_cast<unsigned int>( *p );
Run Code Online (Sandbox Code Playgroud)

如果要从字符串中获取整数,并将const char*解释为指向const char数组的指针,则可以使用上述解决方案之一.


Eri*_*ers 9

C方式:

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

    uintVar = atoi(charVar);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

C++方式:

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

    myStream >> uintVar;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,在任何情况下我都没有检查转换的返回代码以确保它实际工作.


Hel*_*hne 5

在C中,这可以使用atoiC++ via也可以使用cstdlib.

  • 什么`atoi("blah")`回归?那与`atoi(0)`有什么不同? (5认同)
  • 请注意,`atoi()`可能是所有可用选项中最糟糕的选择. (5认同)