使用Stoi()将字符串数组元素转换为C 中的INT

Conversion of string array element to int in c++ using stoi()?

本文关键字:转换 中的 INT 数组元素 字符串 Stoi 使用      更新时间:2023-10-16

我有一个代码:

#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

charstd::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);