【发布时间】:2018-05-31 05:00:14
【问题描述】:
我有一段代码:
#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][0]指的是什么? -
我猜它应该是一个字符串元素。 @AditiRawat
-
至于您的问题,
s[1]是std::string,s[1][0]是字符串s[1]中的单个 字符。std::stoi没有重载,它需要一个字符。 -
这不是 stoi 的解决方案,但也可能有用尝试 int y = s[1][0] - '0';将 ascii 数字转换为 int
标签: c++ arrays string type-conversion int