我试过编写一个简单的数据库程序。问题是,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”); }'。从那里确认创建的文件停止创建的位置。 –