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;
}
}

編集:OK、試してみました

#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);

2番目の引数はオプションですが、最初の引数はconst char *であり、文字列ではありません。この問題を解決する最も簡単な方法は、文字列をC文字列(char *、基本的にはcharの配列)と呼ばれるものに変換することです。これを行うには、c_str()を使用します(これはライブラリの一部です)。

それ以外の場合は、情報をC-strに直接配置して、通常どおりofstreamコンストラクターに渡すことができます。

于 2012-11-13T22:03:57.847 に答える