【问题标题】:I have a lot of error with .append method in c++我在 C++ 中的 .append 方法有很多错误
【发布时间】:2021-12-12 22:02:58
【问题描述】:

我对 C++ 中的 .append 方法有疑问。 这是我的代码:

#include<iostream>
#include<string>
using namespace std;
int main(){
char caratteri[] = {"ciao amici"};
string str = "ciao amici";
string token = "";
for(int i = 0; i<str.length(); i++)
{
    if(str[i+1] == ' '){
        token = "";
    }
    char current_token = str[i];
    token.append(string(current_token));
    i++;
}
}

这是我输出的一部分:

    c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\basic_string.h:397:7: note:   no known                             conversion for argument 1 from 'char' to 'const std::__cxx11::basic_string<char>&'
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\basic_string.h:389:7: note: candidate: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]
       basic_string(const _Alloc& __a) _GLIBCXX_NOEXCEPT
       ^~~~~~~~~~~~
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\basic_string.h:389:7: note:   no known conversion for argument 1 from 'char' to 'const std::allocator<char>&'
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\basic_string.h:380:7: note: candidate: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits   = std::char_traits<char>; _Alloc = std::allocator<char>]
       basic_string()
   ^~~~~~~~~~~~

为什么我会遇到这个问题?我能解决吗? 非常感谢:)

【问题讨论】:

  • 如错误中所述,您无法从 char 创建字符串
  • token.append(string(current_token)) -> token.append(current_token)。您需要附加char,而不是string
  • @NathanOliver token.append(1, current_token) 我想?我建议token += current_token;
  • if(str[i+1] == ' ') -- 这是循环最后一次迭代的越界访问。然后你在for 循环中有这个:i++; -- 老实说,这是一段令人困惑的代码。
  • 试试string(1, current_token)。另见stackoverflow.com/questions/17201590/…

标签: c++ arrays string


【解决方案1】:

您尝试在此处从char 创建std::string

token.append(
    string(current_token)   // <- this part
);

要从单个char 创建std::string,您需要提供您希望char 重复的次数:

token.append(string(1, current_token));

幸运的是,append 具有过载功能,可让您直接执行此操作,而无需创建中间 std::string

token.append(1, current_token);

但最简单的可能是使用operator+= 重载来添加单个char

token += current_token;

还要注意这个

if(str[i+1] == ' ')

i == str.length() - 1 时将访问str[str.length()]。那就是越界访问它。它可能无论如何都会起作用,因为有一个 \0 存储超出范围,但我建议你修复这个逻辑。

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2018-04-09
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多