如何写std :: string到文件?

我想写一个std::stringvariables我接受从用户到一个文件。 我尝试使用write()方法,它写入文件。 但是当我打开文件,我看到的是盒子而不是string。

该string只是一个可变长度的单个单词。 是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();` } 

您目前正在将二进制数据写入到文件的string 。 这个二进制数据可能只包含一个指向实际数据的指针和一个表示string长度的整数。

如果你想写一个文本文件,最好的办法可能是一个“out-file-stream”。 它的行为与std::cout完全一样,但输出写入文件。

以下示例从stdin读取一个string,然后将此string写入文件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()在这里并不是非常必要的:当out范围之外,stream的解构器可以为我们处理这个问题。

有关更多信息,请参阅C ++ – 参考: http : //cplusplus.com/reference/fstream/ofstream/ofstream/

现在,如果您需要以二进制forms写入文件,则应该使用string中的实际数据执行此操作。 获取这个数据最简单的方法是使用string::c_str() 。 所以你可以使用:

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

假设你正在使用std::ofstream来写入文件,下面的代码片断会以可读的forms写入一个std::string文件:

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

从您的stream中的模式中移除ios::binary ,并在您的write.write()使用studentPassword.c_str()而不是(char *)&studentPassword