Skip to content

Instantly share code, notes, and snippets.

@kangzhiheng
Created August 19, 2019 16:18
Show Gist options
  • Save kangzhiheng/3b2b75770d7fbcc8d71e4e9220f2c224 to your computer and use it in GitHub Desktop.
Save kangzhiheng/3b2b75770d7fbcc8d71e4e9220f2c224 to your computer and use it in GitHub Desktop.
字符串转换成int类型说明及示例
#include <iostream>
#include <string> // stoi()函数
using namespace std;
int main()
{
// 将string字符串转换为int类型
/*
atoi()和stoi()函数的区别
1. stoi函数只能将字符串转换为十进制,会对字符串进行检查,如果超过范围,会报错,遇到非法字符同样会停下来,不会报错;
默认要求输入的参数字符串是符合int范围的[-2147483648, 2147483647],否则会runtime error。
2. atoi函数只能将字符串转换为十进制,则不做范围检查,若超过int范围[-2147483648, 2147483647],
则显示-2147483648(溢出下界)或者2147483647(溢出上界)。
stoi头文件:<string>,c++函数
atoi头文件:<cstdlib>,c函数
atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char*类型的,
而stoi()的参数是const string*,不需要转化为 const char*;
*/
vector<string> pStr;
string pS = "135";
// .c_str()函数返回一个指向正规C字符串的指针常量
// 以下三个都正确
cout << atoi(pS.c_str()) << endl;
cout << stoi(pS) << endl;
cout << stoi(pS.c_str()) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment