101

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();`
}
4

3 に答える 3

143

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() );
于 2013-03-13T14:31:04.627 に答える
27

std::ofstreamto write to file を使用していると仮定すると、次のスニペットはstd::stringto file を人間が読める形式で書き込みます。

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
于 2013-03-13T14:31:34.407 に答える