c++ 从字符串中选择字符

sdnqo3pr  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(89)

如何修复以下错误?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string Vorname = "\"John\"\t";
    string Name = Vorname.append("Cena");
    string x = Name[2];
    cout << x;
    return 0;

}

字符串

错误

错误代码:已请求从“__gnu_cxx::__alloc_traits标准::分配器”转换为非标量类型“标准::__cxx11::字符串”{又称为“标准::__cxx11::基本字符串”}|
我的期望:

Output: h

zf9nrax1

zf9nrax11#

你的代码中的问题是这一行:

string x = Name[2];

字符串
Name[2]返回一个char,但你试图将它存储在一个std::string对象中。要解决这个问题,你可以将x的类型从std::string更改为char

char x = Name[2];


此外,hVorname中的第4个字符,因此您需要使用3而不是2

#include <iostream>
#include <string>

int main() {
  std::string Vorname = "\"John\"\t" ;
  std::string Name = Vorname.append("Cena");
  char x = Name[3];
  std::cout << x << '\n';
  return 0;
}

输出:

h

ctzwtxfj

ctzwtxfj2#

C++(与Python不同)有不同的类型来表示单个字符和字符串。
如果希望x为单个字符,请将其更改为

char x = Name[2];

字符串
如果你希望x是一个包含一个字符的字符串,你可以使用substr()方法:

std::string x = Name.substr(2, 1);


此外,正如Sash在his answer中注意到的,h位于字符串中的索引3处。

k3bvogb1

k3bvogb13#

std::string(或std::basic_string)中没有接受一个字符作为第一个参数的构造函数,如

string x = Name[2];

字符串
相反,你可以写例如

string x( 1, Name[2] );


这个构造函数将被调用

basic_string(size_type n, charT c, const Allocator& a = Allocator());


另一种方法是使用接受初始化列表的构造函数。

string x = { Name[2] };


至于你的陈述
我的期望:

Output : h


然后字符'h'存储在字符串Name中,声明如下:

string Vorname = "\"John\"\t" ;
string Name = Vorname.append("Cena") ;


所以你需要在字符串x的声明中使用这个索引,比如

string x = { Name[3] };

相关问题