在C++中将字符串转换为int
时间:2020-02-23 14:29:55 来源:igfitidea点击:
在本文中,我们将研究如何在C++中将字符串转换为int。
通常,我们可能需要将数字字符串转换为整数。
我们可能需要某些方法来快速进行转换
让我们看一下将字符串转换为int的各种方法。
方法1 –使用std :: stoi
要将std :: string对象转换为整数,这是C++中的推荐选项。
这将字符串作为输入并返回整数。
这是一个简单的示例:
#include <iostream>
#include <string>
using namespace std;
int main() {
string inp = "102";
cout << "Input String: " << inp << endl;
//Use std::stoi() to convert string to integer
int res = stoi(inp);
cout << "Integer: " << res << endl;
return 0;
}
输出
Input String: 102 Integer: 102
这也适用于负值字符串。
但是,如果字符串格式不正确,则会抛出" std :: invalid_argument"异常。
因此,如果未验证字符串,则必须在代码中使用异常处理。
#include <iostream>
#include <string>
using namespace std;
int main() {
string inp = "Hello";
cout << "Input String: " << inp << endl;
//Use std::stoi() to convert string to integer
try {
//Wrap up code in try-catch block if string is not validated
int res = stoi(inp);
cout << "Integer: " << res << endl;
}
catch(std::invalid_argument e) {
cout << "Caught Invalid Argument Exception\n";
}
return 0;
}
输出
Input String: Hello Caught Invalid Argument Exception
希望这对如何在C++中将String转换为Integer有所帮助。
我们还将使用C样式的atoi()函数展示另一种方法。
方法2 –使用atoi()
我们可以使用atoi(char * str)将C字符串(char *)转换为整数。
通过首先转换为C字符串,我们可以将此逻辑应用于std :: string对象。
#include <iostream>
#include <string>
using namespace std;
int main() {
string inp = "120";
cout << "Input String: " << inp << endl;
//Convert std::string to C-string
const char* c_inp = inp.c_str();
//Use atoi() to convert C-string to integer
int res = atoi(c_inp);
cout << "Integer: " << res << endl;
return 0;
}
输出
Input String: 120 Integer: 120
如您所见,这为我们提供了与以前相同的结果!

