使用stoi()将字符串数组元素转换为c ++中的int?

问题描述 投票:0回答:2

我有一段代码:

#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函数将int转换为stoi(),那么为什么后面的代码部分会出错呢? 我使用atoi(s[1][0].c_str())尝试过相同但它也给出了错误。

如果我想将第二种类型的元素转换为int,那么替代方法是什么?

c++ arrays string type-conversion int
2个回答
0
投票

s[1]是一个std::string,所以s[1][0]是该字符串中的单个char

std::stoi()作为输入调用char不起作用,因为它只需要一个std::string作为输入,而std::string没有一个只需要一个char作为输入的构造函数。

要做你正在尝试的事情,你需要这样做:

int x = stoi(string(1, s[1][0]));

要么

int x = stoi(string(&(s[1][0]), 1));

你对atoi()的调用不起作用,因为你试图在单个c_str()而不是它所属的char上调用std::string,例如:

int x = atoi(s[1].c_str());

-1
投票

stoi输入一个字符串而不是char。试试这个:

string str(s[0][0]);
int y = stoi(str);
© www.soinside.com 2019 - 2024. All rights reserved.