【问题标题】:Conversion of string array element to int in c++ using stoi()?使用stoi()在c ++中将字符串数组元素转换为int?
【发布时间】: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::strings[1][0] 是字符串 s[1] 中的单个 字符std::stoi 没有重载,它需要一个字符。
  • 这不是 stoi 的解决方案,但也可能有用尝试 int y = s[1][0] - '0';将 ascii 数字转换为 int

标签: c++ arrays string type-conversion int


【解决方案1】:

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

string str(s[0][0]);
int y = stoi(str);

【讨论】:

  • std::string 没有接受char 作为输入的单参数构造函数
【解决方案2】:

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 而不是它所属的std::string 上调用c_str(),例如:

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

【讨论】:

  • 那么,这不能使用 atoi() 来实现吗? int x = atoi(s[1][0]) 也不起作用?
  • 是的,atoi 工作正常。 int x = atoi(&amp;s[1][0])。我忘记了“&”。非常感谢,我今天学到了一些东西:)
  • @sarthak-sopho atoi() 需要一个以空字符结尾的 C 样式字符串作为输入,除非先将其复制到 char[2],否则不能将其传递给单个 char,其中[0] 是字符,[1] 是零
猜你喜欢
  • 2022-07-05
  • 2013-10-19
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2016-08-13
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多