2014-09-11 349 views
5

我試圖刪除.txt文件,但文件名存儲在std::string類型的變量中。問題是,該程序不知道該文件的名稱預先所以我不能只用remove("filename.txt");不存在從「std :: string」到「const char *」的合適轉換函數

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

基本上就是我想要做的是:

remove(fileName2); 

然而,它告訴我

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

回答

14
remove(fileName2.c_str()); 

會做的伎倆。

c_str()成員函數std::string爲您提供了const char * C風格版本的字符串,您可以使用。

+0

關於remove()的信息:http://www.cplusplus.com/reference/cstdio/remove/ – iamantony 2016-05-17 12:29:14

3

您需要將其更改爲:

說,因爲它給我的錯誤,我不能用這個

c_str()將返回字符串作爲const char *類型。

1

當您需要將std::string轉換爲const char*時,您可以使用c_str()方法。

std::string s = "filename"; 
remove(s.c_str()); 
相關問題