c ++将std :: string转换为int,double等,不使用char数组

Ale*_*rov 0 c++ string

在C++中,我只是通过将字符串对象转换为字符数组来完成此操作.有关数组的教程对我来说有点难以理解.但我想在没有数组的情况下进行转换.

我确实知道如何做到这一点:字符串是"1234".之后我将这个文本转换为这样的整数:

if (symol4 == "4") int_var += 4 * 1;
if (symol3 == "3") int_var += 3 * 10;
if (symol3 == "2") int_var += 2 * 100;
if (symol3 == "1") int_var += 1 * 1000; //Don't worry, I'm familiar with cycles, this code is only for explaining my algorithm
Run Code Online (Sandbox Code Playgroud)

我希望你能理解这个想法.

但我不知道这是不是最好的方法.我不知道是否有一个具有允许我这样做的功能的库(如果有的话,我不会感到惊讶).

我不知道如果不使用char数组是一个好主意.但这是一个不同的问题,我稍后会问.

将字符串转换为整数,双精度等的最佳方法是什么,不使用字符数组.

Voo*_*Voo 8

boost::lexical_cast 救援: int result = boost::lexical_cast<int>(input)

如果你不想依赖boost,你可以使用stringstream,例如:

std::stringstream ss;
int result;
ss << input;
ss >> result;
Run Code Online (Sandbox Code Playgroud)

但那是相当迂回的imo

并且不使用atoi- 即使在C中,该功能也存在缺陷,并且随着时间的推移它并没有变得更好.它在解析时发生错误时返回0 - 这有一个明显的问题,即如何区分错误和解析字符串"0".


Kri*_*izz 5

我真的无法得到你的粘贴代码是什么,但在C++中,将字符串转换为整数或浮点数的最佳方法是使用stringstream.

const char* str = "10 20.5";
std::stringstream ss(str);
int x;
float y;

ss >> x >> y;
Run Code Online (Sandbox Code Playgroud)