c++ 如何将string转化int的方法

方法1

C标准库里面,使用atoi(表示 ascii to integer)是把字符串转换成整型数的一个函数int atoi(const char *nptr)

方法2

C++标准库里面,使用stringstream:(stringstream可以用于各种数据类型之间的转换)。
例子:

#include <sstream>
#include <string>
std::string text = "152";
int number;
std::stringstream ss;
ss << text;//可以是其他数据类型
ss >> number; //string -> int

方法3

int stoi (const string& str, size_t* idx = 0, int base = 10);
Parses str interpreting its content as an integral number of the specified base,
which is returned as an int value.If idx is not a null pointer, 
the function also sets the value of idx to the position of the first character 
in str after the number.

题外话

反问,在C++中,如何将数值类型转换为string类型呢?

std::to_string
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Convert numerical value to string,Returns a string with the representation 
of val.

posted on 2021-04-01 22:45  朴素贝叶斯  阅读(3534)  评论(0编辑  收藏  举报

导航