【问题标题】:No suitable conversion function from "std::string" to "const char *" exists不存在从“std::string”到“const char *”的合适转换函数
【发布时间】:2014-11-04 20:39:09
【问题描述】:

我正在尝试删除.txt 文件,但文件名存储在std::string 类型的变量中。问题是,程序事先不知道文件名,所以我不能只使用remove("filename.txt");

string fileName2 = "loInt" + fileNumber + ".txt";

基本上我想做的是:

remove(fileName2);

但是,它告诉我我不能使用它,因为它给了我错误:

不存在从“std::string”到“const char *”的合适转换函数。

【问题讨论】:

    标签: c++ casting


    【解决方案1】:
    remove(fileName2.c_str());
    

    会成功的。

    std::stringc_str() 成员函数为您提供了可以使用的 const char * C 样式版本的字符串。

    【讨论】:

      【解决方案2】:

      您需要将其更改为:

      remove(fileName2.c_str());
      

      c_str() 会将字符串作为const char * 类型返回。

      【讨论】:

        【解决方案3】:

        当您需要将std::string 转换为const char* 时,您可以使用c_str() 方法。

        std::string s = "filename";
        remove(s.c_str());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-23
          • 1970-01-01
          • 2019-01-30
          • 1970-01-01
          相关资源
          最近更新 更多