c++ - 如何将 std::string 写入文件?

标签 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();`
}

最佳答案

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

如果您想写入文本文件,最好的方法可能是使用 ofstream,即“out-file-stream”。它的行为与 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() );

关于c++ - 如何将 std::string 写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15388041/

相关文章:

c++ - 为什么 C++ 不支持动态数组的基于范围的 for 循环?

c++ - 我将如何在 C++ 中将函数作为参数传递

c++ - 为什么不能将模板引用类型用作模板类型别名参数?

c++ - 通过 boost 的递归对。自 boost 1.62 以来变体已损坏

c++ - 作为双指针 (**) 和单指针 (*) 传递的参数

c# - Rfc2898DeriveBytes 是否等同于 PKCS5_PBKDF2_HMAC_SHA1?

c++ - 如何在 C/C++ 中处理大指数的数字?

c# - 将 C++ 方法转换为 C# 时遇到问题

具有新实例参数的 C++ 11 委托(delegate)构造函数?

c++ - 哈希表,其中键是字符串,值是 C++ 中的函数