std :: stringをファイルに書き込む方法は?


89

std::string受け入れている変数をユーザーからファイルに書き込みたい。このwrite()方法を試してみたところ、ファイルに書き込まれました。しかし、ファイルを開くと、文字列の代わりにボックスが表示されます。

文字列は可変長の単一単語のみです。であるstd::string。このために適しまたは私は文字配列か何かを使用する必要があります。

ofstream write;
std::string studentName, roll, studentPassword, filename;


public:

void studentRegister()
{
    cout<<"Enter roll number"<<endl;
    cin>>roll;
    cout<<"Enter your name"<<endl;
    cin>>studentName;
    cout<<"Enter password"<<endl;
    cin>>studentPassword;


    filename = roll + ".txt";
    write.open(filename.c_str(), ios::out | ios::binary);

    write.put(ch);
    write.seekp(3, ios::beg);

    write.write((char *)&studentPassword, sizeof(std::string));
    write.close();`
}

3
コードを見せてください。一般に正しく使用されていればstd::string、これには問題ありません。
役に立たない2013年

2
文字列オブジェクト自体ではなく、文字列の「ペイロード」コンテンツを保存する必要があります(通常、長さと実際のコンテンツへのポインタのみが含まれます)
Mats Petersson 2013年

回答:


124

現在、string-objectのバイナリデータをファイルに書き込んでいます。このバイナリデータは、おそらく実際のデータへのポインタと、文字列の長さを表す整数のみで構成されます。

テキストファイルに書き込みたい場合、これを行うための最良の方法は、おそらくofstream「out-file-stream」を使用することです。とまったく同じように動作しますstd::coutが、出力はファイルに書き込まれます。

次の例では、stdinから1つの文字列を読み取り、この文字列をファイルに書き込みますoutput.txt

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

ここでout.close()は厳密に必要というわけではないことに注意してください。のデコンストラクターは、スコープから外れるとofstreamすぐにこれを処理できoutます。

詳細については、C ++リファレンスを参照してください:http//cplusplus.com/reference/fstream/ofstream/ofstream/

バイナリ形式でファイルに書き込む必要がある場合は、文字列内の実際のデータを使用してこれを行う必要があります。このデータを取得する最も簡単な方法は、を使用することstring::c_str()です。したがって、次を使用できます。

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );

4
改行文字に問題がないようにするには、std :: ios :: binaryを追加する必要がありました
Waddles 2016年

21

を使用しstd::ofstreamてファイルに書き込むと仮定すると、次のスニペットはstd::string人間が読める形式でファイルに書き込みます。

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

0

ios::binaryofstreamのモードからを削除し、のstudentPassword.c_str()代わりに使用(char *)&studentPasswordしますwrite.write()

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.