2012-11-13 146 views
0

我試過編寫一個簡單的數據庫程序。問題是,ofstream不想創建一個新文件。Ofstream沒有正確創建新文件

下面是來自違規代碼的摘錄。

void newd() 
{ 
string name, extension, location, fname; 
cout << "Input the filename for the new database (no extension, and no backslashes)." << endl << "> "; 
getline(cin, name); 
cout << endl << "The extension (no dot). If no extension is added, the default is .cla ." << endl << "> "; 
getline(cin, extension); 
cout << endl << "The full directory (double backslashes). Enter q to quit." << endl << "Also, just fyi, this will overwrite any files that are already there." << endl << "> "; 
getline(cin, location); 
cout << endl; 
if (extension == "") 
{ 
    extension = "cla"; 
} 
if (location == "q") 
{ 
} 
else 
{ 
    fname = location + name + "." + extension; 
    cout << fname << endl; 
    ofstream writeDB(fname); 
    int n = 1; //setting a throwaway inteher 
    string tmpField, tmpEntry; //temp variable for newest field, entry 
    for(;;) 
    { 
     cout << "Input the name of the " << n << "th field. If you don't want any more, press enter." << endl; 
     getline(cin, tmpField); 
     if (tmpField == "") 
     { 
      break; 
     } 
     n++; 
     writeDB << tmpField << ": |"; 
     int j = 1; //another one 
     for (;;) 
     { 
      cout << "Enter the name of the " << j++ << "th entry for " << tmpField << "." << endl << "If you don't want any more, press enter." << endl; 
      getline(cin, tmpEntry); 
      if (tmpEntry == "") 
      { 
       break; 
      } 
      writeDB << " " << tmpEntry << " |"; 
     } 
     writeDB << "¬"; 
    } 
    cout << "Finished writing database. If you want to edit it, open it." << endl; 
} 
} 

編輯:好的,只是試圖

#include <fstream> 
using namespace std; 
int main() 
{ 
ofstream writeDB ("C:\\test.cla"); 
writeDB << "test"; 
writeDB.close(); 
return 0; 
} 

,並沒有工作,所以它是訪問權限的問題。

+0

給出了一個程序執行的例子和你輸入的內容。 –

+1

當你以這種方式輸入字符串時,你也不需要「雙反斜槓」,只能用於代碼中的字符串文字。 – HerrJoebob

+5

將您的來源減至*僅*顯示問題。然後確認這確實是*問題。我猜想,你試圖在一個不存在的有趣位置打開一個文件。一個簡單的程序來驗證'std :: ofstream'如預期那樣工作:'#include int main(){std :: ofstream out(「empty.txt」); }'。從那裏確認創建的文件停止創建的位置。 –

回答

3
ofstream writeDB(fname); //-> replace fname with fname.c_str() 

如果您查找的ofstream的構造函數的文檔,你會看到類似這樣的: 明確的ofstream(爲const char *文件名的ios_base ::用於openmode模式=的ios_base ::出來);

第二個參數是可選的,但第一個參數是一個const char *,而不是一個字符串。爲了解決這個問題,最簡單的方法是將你的字符串轉換爲一個叫做C字符串的字符串(char *,它基本上是一個字符數組)。要做到這一點只需使用c_str()(它是庫的一部分)。

除此之外,您可以直接將信息放在C-str上,然後將其正常傳遞給ofstream構造函數。

+4

C++ 11添加了一個[構造函數](http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream),它接受一個'std :: string'參數,但如果OP使用的是較舊的編譯該代碼甚至不應該編譯。 – Praetorian

+0

謝謝你,我補充說,但它仍然無法正常工作。我正在使用Visual Studio Express 2012 BTW。謝謝大家! –