これはおそらくあなたにとって非常に厄介な質問です:関数からifstreamを返すにはどうすればよいですか?
基本的に、ユーザーからデータベースのファイル名を取得する必要があり、そのファイル名のデータベースが存在しない場合は、ユーザー用にそのファイルを作成する必要があります。私はそれを行う方法を知っていますが、ファイルを作成した後にプログラムを再起動するようにユーザーに依頼することによってのみです。可能であればユーザーの不便を避けたかったのですが、以下の関数はgccでコンパイルされません。
ifstream getFile() {
string fileName;
cout << "Please enter in the name of the file you'd like to open: ";
cin >> fileName;
ifstream first(fileName.c_str());
if(first.fail()) {
cout << "File " << fileName << " not found.\n";
first.close();
ofstream second(fileName.c_str());
cout << "File created.\n";
second.close();
ifstream third(fileName.c_str());
return third; //compiler error here
}
else
return first;
}
編集:申し訳ありませんが、コンパイラエラーがどこで何であったかを伝えるのを忘れました:
main.cpp:45: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here
編集:Remusが提案したように、代わりにポインターを返すように関数を変更し、main()の行を「ifstreamdatabase = * getFile()」に変更しました。今度はこのエラーが再び発生しますが、今回はmain()の行にあります。
main.cpp:27: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here