相关疑难解决方法(0)

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

我想写一个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();`
}
Run Code Online (Sandbox Code Playgroud)

c++

71
推荐指数
2
解决办法
20万
查看次数

将字符串写入二进制文件C++

我在将字符串写入二进制文件时遇到问题.这是我的代码:

ofstream outfile("myfile.txt", ofstream::binary);
std::string text = "Text";
outfile.write((char*) &text, sizeof (string));
outfile.close();
Run Code Online (Sandbox Code Playgroud)

然后,我尝试阅读它,

char* buffer = (char*) malloc(sizeof(string));
ifstream infile("myfile.txt", ifstream::binary);    
infile.read(buffer, sizeof (prueba));
std::string* elem = (string*) buffer;
cout << *elem;
infile.close();
Run Code Online (Sandbox Code Playgroud)

我不能让它工作.对不起,我只是绝望了.谢谢!

c++ string malloc file

6
推荐指数
3
解决办法
3万
查看次数

标签 统计

c++ ×2

file ×1

malloc ×1

string ×1