Ofstream没有正确创建新文件

时间:2012-11-13 21:57:58

标签: c++ visual-studio-2012 creation 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;
}

这不起作用,因此是访问权限问题。

1 个答案:

答案 0 :(得分:3)

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

如果查找ofstream构造函数的文档,您将看到如下内容: 显式的ofstream(const char * filename,ios_base :: openmode mode = ios_base :: out);

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

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