如何将std::string写入文件

How to write std::string to file?

本文关键字:文件 string std      更新时间:2023-10-16

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

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

如果你想写一个文本文件,最好的方法可能是使用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;
}

请注意,out.close()在这里并不是严格必要的:只要out超出作用域,ofstream的解构器就可以为我们处理这个问题。

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

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

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

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

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

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

如果您有fmt可用:

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

但是你不是真的在给文件写密码,对吧?