我試過編寫一個簡單的數據庫程序。問題是,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;
}
,並沒有工作,所以它是訪問權限的問題。
給出了一個程序執行的例子和你輸入的內容。 –
當你以這種方式輸入字符串時,你也不需要「雙反斜槓」,只能用於代碼中的字符串文字。 – HerrJoebob
將您的來源減至*僅*顯示問題。然後確認這確實是*問題。我猜想,你試圖在一個不存在的有趣位置打開一個文件。一個簡單的程序來驗證'std :: ofstream'如預期那樣工作:'#include int main(){std :: ofstream out(「empty.txt」); }'。從那裏確認創建的文件停止創建的位置。 –