gpt4 book ai didi

c++ - 为什么我无法从文件中读取对象?

转载 作者:行者123 更新时间:2023-12-02 10:17:23 25 4
gpt4 key购买 nike

我想将字符串对象输出到文件中并取回,但是我的代码根本不输出任何内容。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void main()
{
// open file for binary input/output
fstream binary("data.txt", ios::binary);

// create random string
string str1 = "fgh";

// write down string object to the file
binary.write(reinterpret_cast<char*>(&str1), sizeof(str1));

// create second string
string str2;

// get str1 to str2
binary.read(reinterpret_cast<char*>(&str2), sizeof(str1));

// print second string
cout << str2;
}

最佳答案

我认为以下代码是不言自明的。

您不需要(也不应该使用)二进制文件来存储std::string。而是将它们存储在由定界符分隔的文本文件中。

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() { // void main doesn't work on C++

// open file for binary input/output
fstream file("data.txt", ios::in | ios::out); // .txt file is not a binary file dude

// check if file already exists or not
// file will not be automatically created because ios::in mode is also being used
if (not file) {
cerr << "No such file present!" << endl;
return -1;
}

// create random string
string str1 = "fgh";

// write down string object to the file
// binary.write(reinterpret_cast<char*>(&str1), sizeof(str1));
file << str1 << endl; // if you are removing std::endl from here then add std::flush

// set get pointer at beginning because write operation has moved it to end
// it is always better to use two file objects (one ifstream and one ofstream) for such projects.
file.seekg(ios::beg);

// create second string
string str2;

// get str1 to str2
// binary.read(reinterpret_cast<char*>(&str2), sizeof(str1));
file >> str2;

// print second string
cout << str2;

return 0;
}

关于c++ - 为什么我无法从文件中读取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61463646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com