![](/img/trans.png)
[英]Converting a substring char to an int from a string value then assigning it to an int variable
[英]Pulling a single char from a string and converting it to int
我试图从字符串中提取特定的char并将其转换为int。 我已经尝试了以下代码,但我不清楚它为什么不起作用,也无法找到转换的方法。
int value = 0;
std::string s = "#/5";
value = std::atoi(s[2]); // want value == 5
您可以从一个char创建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;
}
你可以写:
std::string s = "#/5";
std::string substring = s.substr(2, 1);
int value = std::stoi(substring);
使用std::string
的substr
方法拉出要作为整数解析的子字符串,然后使用stoi
(它采用std::string
)而不是atoi
(采用const char *
)。
您应该仔细阅读atoi()
的手册页。 实际的原型是:
int atoi(const char *string)
您正在尝试传递单个字符而不是指向字符数组的指针。 换句话说,通过使用s[2]
您将取消引用指针。 相反,您可以使用:
value = std::atoi(s+2);
或者:
value = std::atoi(&s[2]);
此代码不会取消引用指针。
std::atoi
的参数必须是char*
,但s[2]
是char
。 你需要使用它的地址。 要从std::string
获取有效的C字符串,您需要使用c_str()
方法。
value = std::atoi(&(s.c_str()[2]));
你应该得到一个错误,说参数不是正确的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.