2012-11-13 95 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。谢谢大家! –