2012-07-27 19 views
2
void searchString(const string selection,const string filename) 
{ 
    ifstream myfile; 
    string sline; 
    string sdata; 
    myfile.open(filename); 
    while(!myfile.eof()) 
    { 
     getline(myfile,sline); 
     sdata = sdata + sline; 
    } 

如何使用C++如何使用一個變量ifstream的

最初我是使用file.txt的,而不是字符串的文件名作爲myfile.open(文件名),但如果我使用過的變量由功能,如字符串的文件名,它給我一個錯誤,作爲接着

myfile.open("file.txt"); 

錯誤消息:

main.cpp:203:25: error: no matching function for call to ‘std::basic_ifstream<char>::open(const string&)’ 
main.cpp:203:25: note: candidate is: 
/usr/include/c++/4.6/fstream:531:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode] 
/usr/include/c++/4.6/fstream:531:7: note: no known conversion for argument 1 from ‘const string {aka const std::basic_string<char>}’ to ‘const char*’ 
make: *** [main.o] Error 1 
+0

你的代碼應該在C++ 11中工作。然而,它仍然值得指出:http://stackoverflow.com/questions/5105476/attempting-to-pass-string-to-stdifstream-as-argument?rq=1 – chris 2012-07-27 04:40:12

回答

7

構造對於std::ifstream::open(對於C的特定標準++您使用)不允許std::string參數,所以必須使用:

myfile.open(filename.c_str()); 

構造函數需要鍵入const char *它可以從一個std::string對象使用得到其成員函數爲c_str()

+0

從錯誤消息,它看起來像是如果他們傳遞'-std = C++ 11'代碼將編譯。 – 2012-07-27 05:28:32

+0

main.cpp:203:26:error:'std :: string'沒有名爲'cstr'的成員 – user1548465 2012-07-27 06:50:13

+1

@ user1548465:它的'c_str()'不是'cstr()'。下劃線使世界有所不同:) – dreamlax 2012-07-27 09:01:06

相關問題