如何将std :: string写入文件?

Sla*_*shr 71 c++

我想写一个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();`
}
Run Code Online (Sandbox Code Playgroud)

JSQ*_*reD 97

您当前正在将string-object中的二进制数据写入您的文件.这个二进制数据可能只包含一个指向实际数据的指针,以及一个表示字符串长度的整数.

如果要写入文本文件,最好的方法可能是使用ofstream"out-file-stream".它的行为与此类似std::cout,但输出将写入文件.

以下示例从stdin读取一个字符串,然后将此字符串写入该文件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;
}
Run Code Online (Sandbox Code Playgroud)

注意out.close()这里并不是非常必要的:解析器ofstream可以out在超出范围时立即为我们处理.

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

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

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
Run Code Online (Sandbox Code Playgroud)

  • 我不得不为此添加std :: ios :: binary,以避免换行符问题 (3认同)
  • @caoanan 它是为了演示 API。我还在正文中提到,当变量超出范围时,它会自动发生。无论如何,“close()”是幂等的,因此多次调用它并没有什么坏处。 (3认同)

ste*_*fan 14

假设您使用的std::ofstream是写入文件,以下代码段将以std::string人类可读的形式写入文件:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
Run Code Online (Sandbox Code Playgroud)