Почему я не могу прочитать объект из файла? - PullRequest
0 голосов
/ 27 апреля 2020

Я хочу вывести строковый объект в файл и получить его обратно, но мой код вообще ничего не печатает.

#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;
}

1 Ответ

0 голосов
/ 27 апреля 2020

Я думаю, что код, написанный ниже, не требует пояснений.

Вам не нужен (и не должен использоваться) двоичный файл для хранения 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...