首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将std::string写入文件?

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

Stack Overflow用户
提问于 2013-03-13 22:25:20
回答 3查看 276.2K关注 0票数 98

我想要将一个从用户接受的std::string变量写到一个文件中。我尝试使用write()方法,它会写入文件。但当我打开文件时,我看到的是方框而不是字符串。

该字符串只是一个长度可变的单个单词。std::string是否适用于此,或者我是否应该使用字符数组或其他什么。

代码语言:javascript
复制
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();`
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-03-13 22:31:05

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

如果你想写一个文本文件,最好的方法可能是使用一个ofstream,一个"out- file -stream“。它的行为与std::cout完全相同,但是输出被写到一个文件中。

下面的示例从标准输入中读取一个字符串,然后将此字符串写入文件output.txt

代码语言:javascript
复制
#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()。因此,您可以使用:

代码语言:javascript
复制
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
票数 140
EN

Stack Overflow用户

发布于 2013-03-13 22:31:34

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

代码语言:javascript
复制
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
票数 27
EN

Stack Overflow用户

发布于 2013-10-16 05:13:40

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15388041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档