c++ - 从字符串中提取单个字符并将其转换为 int

标签 c++ string char atoi

我正在尝试从字符串中提取特定的字符并将其转换为整数。我尝试了以下代码,但我不清楚为什么它不起作用,也无法找到进行转换的方法。

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/

相关文章:

python - 使用python将一个单词移动到行尾

java - 如何更改方法中字符串的字符? (相同字符,随机顺序)

c++ - 为什么我不能正常初始化 typedef struct string 或 char?

c++ - LLVM 编译器 2.0 : Warning with "using namespace std;"

c++ - 我的 C++ 设计不一致

c++ - 让 dll 包含在 Visual Studio 中工作

c++ - 将 char 添加到变量名称

c++ - 在 STL 优先级队列 C++ 中实现 decreaseKey

c# - 如何衡量两个字符串之间的相似度?

python - 如何在Python 3中使用for循环计算字符串内的单词数