0

我试图编写一个简单的数据库程序。问题是 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;
}

这没有用,所以是访问权限问题。

4

1 回答 1

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

如果您查找 ofstream 构造函数的文档,您会看到类似:explicit ofstream ( const char * filename, ios_base::openmode mode = ios_base::out );

第二个参数是可选的,但第一个是 const char*,而不是字符串。要解决这个问题,最简单的方法是将字符串转换为 C 字符串(char*,基本上是一个字符数组);为此,只需使用 c_str() (它是库的一部分)。

除此之外,您可以直接将信息放在 C-str 上,然后将其正常传递给 ofstream 构造函数。

于 2012-11-13T22:03:57.847 回答