0

これまでのところ、問題なくユーザーからファイルの場所とファイル名を取得するためにプログラムをダウンさせました。ofstreamこの問題は、ユーザーから提供されたファイルの場所を使用してオブジェクトを作成しようとしたときに発生します。私は基本的append()に文字列ライブラリの関数を使用して、ファイルの場所c:\users\user\my documents\"file"を私が作業している標準形式にします。オブジェクトなしでコードをテストしましたが、ofstream問題ないようです。そのため、ofstream オブジェクトが文字列変数で指定されたファイルの場所 (filelocation) を参照しない理由がわかりません。

現時点では、プログラムはどこかに Hello を含むファイルを作成する必要がありますが、これは行われておらず、コードはコンパイルを拒否しています。将来的にはどこかでユーザー入力を取得する計画がありますが、これは先に進む前に克服する必要がある小さなハードルです。

#include <fstream>
#include <string> 
#include <iostream>
using namespace std ;

int main() 
{
string text = "Hello" ;
string title ;
string usertitle ;
string filelocation = "C:/Users/" ;
string user ;
cout << "Input a title for your file: " ;
cin >> title ;
title.insert(title.length() , ".txt" ) ;
cout << "Your title is: " << title << endl ;
cout << endl << "Input the username associated with your computer (Caps Sensitive): " ;
cin >> user ;
filelocation.append( user ) ;
filelocation.append("/My Documents/") ;
filelocation.append(title) ;
filelocation.insert(0, "\"") ;
filelocation.insert(filelocation.length() , "\"" ) ;
cout << "Your chosen file name and location is: " << filelocation << endl ;

ofstream writer( filelocation.c_str() ) ;

if (! writer )
{
    cout << "Error opening file for output" << endl ;
    return -1 ; //Signal an error then exit the program
}
else
{
    writer << text << endl ;
    writer.close() ;
}
return 0 ;
}

ご協力いただきありがとうございます。

4

1 に答える 1

1

std::ofstreamコンストラクタの引数は確認しましたか?だと思いますconst char *

コンストラクタは次のように宣言されます。

explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);

したがって、あなたの場合、std::string引数としてa を使用します。

   std::ofstream writer(filelocation.c_str());
于 2013-09-17T18:35:01.000 に答える