如何将 std: : 字符串写入文件?

我想写一个 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();`
}
310325 次浏览

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() );

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

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

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

If you have fmt available:

#include <fmt/os.h>
// ...
fmt::output_file(filename).print("{}\0\0{}", ch, studentPassword);
// ...

But you are not really writing a password to a file, right?