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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25778263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:25:28  来源:igfitidea点击:

No suitable conversion function from "std::string" to "const char *" exists

c++casting

提问by user3216887

I am trying to delete a .txtfile but the filename is stored in a variable of type std::string. The thing is, the program does not know the name of the file beforehand so I can't just use remove("filename.txt");

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

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

Basically what I want to do is:

基本上我想做的是:

remove(fileName2);

However, it tells me that I cannot use this because it gives the me error:

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

No suitable conversion function from "std::string" to "const char *" exists.

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

回答by paxdiablo

remove(fileName2.c_str());

will do the trick.

会做的伎俩。

The c_str()member function of a std::stringgives you the const char *C-style version of the string that you can use.

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

回答by PomfCaster

You need to change it to:

您需要将其更改为:

remove(fileName2.c_str());

c_str()will return the string as a type const char *.

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

回答by justanothercoder

When you need to convert std::stringto const char*you can use the c_str()method.

当您需要转换std::stringconst char*您可以使用该c_str()方法。

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