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


86

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

3
请显示您的代码。通常,如果正确使用,std::string就可以做到这一点。
没用的2013年

2
您需要保存字符串的“有效负载”内容,而不是字符串对象(通常只包含一个长度和一个指向实际内容的指针)
Mats Petersson 2013年

Answers:


120

您当前正在将string-object中的二进制数据写入文件。该二进制数据可能仅包含指向实际数据的指针,以及代表字符串长度的整数。

如果要写入文本文件,最好的方法可能是使用ofstream“输出文件流”。它的行为与完全相同std::cout,但输出将写入文件。

以下示例从stdin读取一个字符串,然后将此字符串写入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;
}

请注意,out.close()此处并不一定要这样:的析构ofstream函数可以out在超出范围时立即为我们处理此问题。

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

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

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

3
我必须添加std :: ios :: binary才能使换行符不出现问题
Waddles

19

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

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

0

ios::binary从ofstream中的模式中删除,然后使用studentPassword.c_str()而不是(char *)&studentPasswordwrite.write()

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.