Skip to content

Instantly share code, notes, and snippets.

@imsjz
Created February 24, 2020 05:36
Show Gist options
  • Save imsjz/2967db6073645f10f1c93a4cc01f4aa0 to your computer and use it in GitHub Desktop.
Save imsjz/2967db6073645f10f1c93a4cc01f4aa0 to your computer and use it in GitHub Desktop.
c语言风格和c++风格stirng转int
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// c语言风格将string转为int, 缺点是不会进行数字检查,遇到非法字符就终止了,直接输出0
void CStyle() {
string str = "123s";
int a = atoi(str.c_str());
// 支持多进制转换
int b = strtol(str.c_str(), nullptr, 10);
cout << a << " " << b << endl;
}
// c++语言风格
void CppStyle() {
string str1 = "asq.";
// int c= stoi(str1); //exception
string str2 = "12343";
int d = stoi(str2);
cout << d << endl;
}
// 自定义转换
int StringToInt(const string& s) {
int v;
stringstream ss;
ss << s;
ss >> v;
return v;
}
int main() {
CStyle();
CppStyle();
int i = StringToInt("2.3");
cout << i << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment