dimanche 14 mars 2021

How to write the value of a list's iterator to a binary file?

In the following code, I defined five different strings and stored each of them in a list. Then I used an iterator to get every string stored in the list to write it to a binary file. The problem is to cast the address of the value of the iterator to a pointer to char to write it to the binary file but whatever I try to do this casting, I face this compile-time error:

invalid cast from type ‘std::__cxx11::liststd::__cxx11::basic_string<char >::iterator’ {aka ‘std::_List_iteratorstd::__cxx11::basic_string<char >’} to type ‘char*’

What's the best way to resolve this problem?

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

int main()
{
  fstream File("../target.bin", ios::binary | ios::trunc);
  string contents[5] = {"David", "Max", "Gerrard", "John", "Donald"};
  list<string> container;

  for(register unsigned counter = 0; counter < 5; counter++)
    container.push_back(contents[counter]);

  for(register list<string>::iterator itr = container.begin(); itr != container.end(); itr++)
  {
    File.write((char*)itr, sizeof(string));
  }

  File.close();
  return EXIT_SUCCESS;
}

Aucun commentaire:

Enregistrer un commentaire