2012-02-10 97 views
0

我的IDE在最後一行有「filename」變量。有人能指出我爲什麼嗎?ofstream variable.open是否支持預定義的字符串變量?

switch(filename_selection) 
    { 
     case 1: filename_selection = 1; 
     filename = "foo3.sql"; 
     break; 

     case 2: filename_selection = 2; 
     filename = "foo2.sql"; 
     break; 

     case 3: filename_selection = 3; 
     filename = "foo1.sql"; 
     break; 

     default: 
     cout << "Invalid selection." << endl; 
     break; 
    } 
    ofstream File; 
    File.open(filename, ios::out | ios::trunc); 
+1

* What * issues ...?你的'filename'是如何定義的? – Xeo 2012-02-10 02:03:52

+0

此外,您將'filename_selection'重新賦值給它的原因是什麼? – Xeo 2012-02-10 02:13:11

+0

菜鳥錯誤,真的。讀入此。 – Switchkick 2012-02-10 02:29:57

回答

4

我的水晶球是今天有點陰,但我想我能看到的東西......

<psychic-powers>
filename被聲明爲std::string filename;。不幸的是,在C++ 03中,std::(i|o)fstream類沒有接受std::string變量的構造函數,只有char const*變量。

解決方法:通過filename.c_str()
</psychic-powers>

+0

它的工作!你神祕感的力量是奇妙的! – Switchkick 2012-02-10 02:15:02

1

假設類型的std :: string的,那麼你就不能直接傳遞到ofstream的構造函數:你需要c_str()的功率

switch(filename_selection) 
{ 
    case 1: 
    //filename_selection = 1; WHAT IS THIS? 
    filename = "foo3.sql"; 
    break; 

    case 2: 
    ///filename_selection = 2; ??? 
    filename = "foo2.sql"; 
    break; 

    case 3: 
    ///filename_selection = 3; ??? 
    filename = "foo1.sql"; 
    break; 

    default: 
    cout << "Invalid selection." << endl; 
    break; 
} 
ofstream File; 
File.open(filename.c_str(), // <<< 
      ios::out | ios::trunc); 

此外,您似乎也誤解了如何使用switch statement

+0

感謝您的提示! – Switchkick 2012-02-10 02:31:49