【问题标题】:How to write std::string to file?如何将 std::string 写入文件?
【发布时间】:2013-03-01 13:10:17
【问题描述】:

我想将用户接受的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();`
}

【问题讨论】:

  • 请出示您的代码。一般来说,如果正确使用,std::string 就可以了。
  • 您需要保存字符串的“有效负载”内容,而不是字符串对象本身(通常只包含长度和指向实际内容的指针)

标签: c++


【解决方案1】:

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

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

以下示例从标准输入读取一个字符串,然后将该字符串写入文件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() );

【讨论】:

  • 我必须添加 std::ios::binary 才能使换行符没有问题
  • out.close() ?两次?不好的答案
  • @caoanan 是为了演示 API。我还在正文中提到,当变量超出范围时它会自动发生。无论如何,close() 是幂等的,所以多次调用它并没有什么坏处。
【解决方案2】:

假设您使用 std::ofstream 写入文件,以下 sn-p 将以人类可读的形式将 std::string 写入文件:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-16
      • 2015-02-15
      • 2021-07-22
      • 2019-12-11
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多