Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

c++ - How to write std::string to file?

I want to write a std::string variable I am accepting from the user to a file. I tried using the write() method and it writes to the file. But when I open the file I see boxes instead of the string.

The string is only a variable length single word. Is std::string suitable for this or should I use a character array or something.

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();`
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.

If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.

The following example reads one string from stdin, and then writes this string to the file 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;
}

Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.

For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/

Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...