【发布时间】:2019-02-23 15:26:45
【问题描述】:
【问题讨论】:
-
字符串转整数需要使用atoi或stoi。
-
你能解释一下吗??
【问题讨论】:
你不能将字符串转换为整数。但是,你可以使用 stoi() 获取字符串数值,然后将其分配给整数:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
cout << "stoi(\"" << str1 << "\") is "
<< myint1 << '\n';
cout << "stoi(\"" << str2 << "\") is "
<< myint2 << '\n';
cout << "stoi(\"" << str3 << "\") is "
<< myint3 << '\n';
return 0;
}
Output:
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337
还有其他方法,例如使用 stringstream,您可能想看看。希望它有所帮助。
【讨论】: