在C++中,将字符串转换为整型数字是一个比较常见的操作,有多种方法可以实现。下面介绍其中几种常用的方法:
1. 使用atoi函数
atoi函数是C/C++中的一个库函数,它可以将字符串转换为整型数字,其定义如下:
int atoi(const char *str);
使用atoi函数时,需要把要转换的字符串作为参数传入,它会将字符串转换为整型数字并返回,例如:
int num = atoi("123"); // num的值为123
2. 使用stringstream类
stringstream类是C++中的一个类,它可以将字符串转换为整型数字,其使用方法如下:
#includeint main() { std::stringstream ss; ss << "123"; int num; ss >> num; // num的值为123 return 0; }
3. 使用strtol函数
strtol函数是C/C++中的一个库函数,它可以将字符串转换为整型数字,其定义如下:
long int strtol(const char *str, char **endptr, int base);
使用strtol函数时,需要把要转换的字符串作为第一个参数传入,它会将字符串转换为整型数字并返回,例如:
long int num = strtol("123", NULL, 10); // num的值为123
4. 使用C++ 11中的stoi函数
C++ 11中引入了stoi函数,它可以将字符串转换为整型数字,其定义如下:
int stoi(const string& str, size_t *idx = 0, int base = 10);
使用stoi函数时,需要把要转换的字符串作为参数传入,它会将字符串转换为整型数字并返回,例如:
int num = stoi("123"); // num的值为123
以上是C++中将字符串转换为整型数字的几种常用方法,可以根据自己的需要选择合适的方法进行实现。