我正在尝试从字符串中提取特定的字符并将其转换为整数。我尝试了以下代码,但我不清楚为什么它不起作用,也无法找到进行转换的方法。
int value = 0;
std::string s = "#/5";
value = std::atoi(s[2]); // want value == 5
最佳答案
您可以从一个字符创建 std::string
并使用 std::stoi
转换为整数。
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int value = 0;
string s = "#/5";
value = stoi(string(1, s[2])); //conversion
cout << value;
}
关于c++ - 从字符串中提取单个字符并将其转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49418426/