2016-04-24 10 views
-1

私のC++プロジェクトをコンパイルしているとき、私は理解できません。私のエラーは、以下のこのコードセクションにスローされます。<string int>をファイルに書き込む - 'operator <<'と一致しないものはありません

void twogramsToFile(const map <string,int> twogram, const string outputfile) { 
    ofstream myfile (outputfile); 

    for (auto &x : twogram) { 
    outputfile << x.first << " " << x.second << "\n"; //this line causes the error 
    } 

    myfile.close(); 
} 

そして、私が取得エラーメッセージは、このいずれかになります。

no match for ‘operator<<’ (operand types are ‘const string {aka const std::__cxx11::basic_string<char>}’ and ‘const std::__cxx11::basic_string<char>’) 

私は< <オペレータは種類に建設のために定義されていたと思いました。

+0

*組み込み型の*のために<<演算子が定義されていると考えました。* - ' 'は組み込みではありません。 – PaulMcKenzie

答えて

5

私は< <演算子が組み込み型に対して定義されていると考えました。

これは不満ではなく、左側です。 からconst文字列にストリーミングすることはできますが、のconst文字列にストリーミングすることはできません。試してください

myfile << ... 
+2

エラーメッセージを非常に慎重に読んだら、実際には 'operator <<'への引数は*両方* 'std :: string'です。 –

+0

ストリングからどのようにストリーミングしますか? –

+0

['ostream&operator <<(ostream&、const string&)'](http://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt)を使用すると、 – Useless

1

出力文字列に出力します。あなたが行う必要があります。

myfile << ... 
1

をあなたがconst std::stringにストリーミングしようとしている、私はそれが代わりにstd::stringパラメータoutputfile

​​

べきであると思います。

void twogramsToFile(const std::map<std::string, int>& twogram, const std::string& outputfile) 
0

変更行:

outputfile << x.first << " " << x.second << "\n"; //this line causes the error 

へ:

myfile << x.first << " " << x.second << "\n"; 

をところで、次のように

はまた、あなたは不必要なコピーを避けるために、参照することによりstd::mapstd::string渡す必要があります文字列はC++の組み込み型ではありません

関連する問題