使用Stoi()将字符串数组元素转换为C 中的INT
Conversion of string array element to int in c++ using stoi()?
我有一个代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
//ios_base::sync_with_stdio(false);
string s[5];
s[0] = "Hello";
s[1] = "12345";
cout << s[0] << " " << s[1] << "n";
cout << s[0][0] << " " << s[1][1] << "n";
int y = stoi(s[1]); //This does not show an error
cout <<"y is "<< y << "n";
//int x = stoi(s[1][1]); //This shows error
//cout <<"x is "<< x << "n";
return 0;
}
此代码的输出是:
Hello 12345
H 2
y is 12345
,但是当我删除时显示出错误
int x = stoi(s[1][0]);
cout <<"x is "<< x << "n";
如果在这两种情况下,string
都使用stoi()
转换为int
函数为什么代码的后面部分给出错误?
我使用atoi(s[1][0].c_str())
尝试了相同的尝试,但也会出现错误。
如果我想将第二种元素转换为int?
s[1]
是 std::string
,因此 s[1][0]
是该字符串中的单个 char
。
用char
将std::stoi()
调用是输入不起作用,因为它仅将std::string
作为输入,而std::string
没有仅将单个char
作为输入的构造函数。
要做您正在尝试的事情,您需要做到这一点:
int x = stoi(string(1, s[1][0]));
或
int x = stoi(string(&(s[1][0]), 1));
您对atoi()
的呼叫不起作用,因为您试图在单个char
上致电c_str()
,而不是std::string
,例如:
int x = atoi(s[1].c_str());
stoi作为输入字符串而不是字符尝试以下操作:
string str(s[0][0]);
int y = stoi(str);
相关文章:
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 了解 GLM- openGL 中的相机转换
- C++中的双指针类型转换
- 了解双精度转换与整数转换中的整数与截断关系
- C++要包含在词法强制转换中的头文件
- 是否可以使用 SAPI 忽略Microsoft文本到语音转换中的单词
- 处理字符到QString转换中的ASCII字符
- 反射格雷码到二进制转换中的幻数
- 自定义文本到语音转换中的语音
- C++ 为转换中的多数组错误增加值
- Java C/C++ 转换中的指针
- 标准::转换中的 [] const_iterator::value_type 是什么意思
- HSV 转换中的浮点错误
- 动态转换中的错误
- c++int存储为char*转换中的字符,无需任何API
- 引用类型转换中的c++虚函数
- 不同的编译器用来处理数字转换中的溢出的常见策略是什么?
- 隐式常量转换中的溢出[-Woverflow]
- 从c++到c# . net紧凑框架结构转换中的问题