【问题标题】:C++: Cannot convert string to char*?C++:无法将字符串转换为 char*?
【发布时间】:2021-09-27 07:58:11
【问题描述】:

我正在尝试使用以下代码在 C++ 中打印Deque 的第一项(顶部项):

#include <queue>
#include <deque>
#include <string>

using namespace std;

int main(int argc, char *argv[]){
    deque<string> commandHistory;

    for (int i = 0; i < 2; i++) {
        commandHistory.push_back("asdf");
    }

    printf(commandHistory.at(1));
    return 0;
}

但是,我在 printf 语句中遇到错误:

错误:无法转换 '__gnu_cxx::__alloc_traitsstd::allocator<:__cxx11::basic_string>

,std::__cxx11::basic_string >::value_type’ {aka ‘std::__cxx11::basic_string’} 到 ‘const char*’

但是,我不能像这样将 commandHistory.at(1) 转换为 const char*

printf((const char*) commandHistory.at(1));

【问题讨论】:

标签: c++ data-structures casting queue


【解决方案1】:

即使您的问题同时标记为 C 和 C++,我还是会删除 C 标记,因为您的代码是 C++ 而非 C。

printf 的文档在这里:https://en.cppreference.com/w/cpp/io/c/fprintf

该函数的要点是它至少需要 1 个参数:所谓的格式字符串,正如签名所说,是 const char*

char *std::string 是完全不同的类型。 std::string 是一个类,char * 只是一个指向内置类型的指针。您的 std::deque 包含 std::string 对象。

很方便,std::string 提供了一个到 const char* 的转换功能,正好适合这些情况。

因此,一个有效的 sn-p 将是:

// looks like you were missing cstdio
#include <cstdio>
#include <deque>
#include <string>
using namespace std;

int main(int argc, char *argv[]){
    deque<string> commandHistory;

    for (int i = 0; i < 2; i++) {
        commandHistory.push_back("asdf");
    }
    // note the `c_str` method call to get a c-style string from a std::string
    printf(commandHistory.at(1).c_str());
    return 0;
}

就像编译器说的那样,您不能(使用 static_cast)将 std::string 转换为 char*,但您可以使用 .c_str() 获得所需的 const char*。

正如其他提到的,您还可以包含iostream 并使用std::cout 其中knows 对每种类型(const char*、std::string、int 等)做什么(通过重载)和也可以与您自己的类型一起使用。

编辑:更清晰/更清晰的代码/解释。

【讨论】:

  • 以这种方式使用printf 通常是不安全的:如果双端队列曾经包含带有 printf 格式说明符的字符串,那么当未提供匹配的参数时,您将获得未定义的行为。至少使用printf("%s", commandHistory.at(1).c_str())
  • (希望代码尽可能接近原始代码)仍然 +1,我可以根据您提到的内容添加编辑!
猜你喜欢
  • 1970-01-01
  • 2018-03-27
  • 2013-05-13
  • 2012-01-16
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
相关资源
最近更新 更多