String to Char conversion

Hi, I am trying to write this simple program for school where I need to convert a text file to a binary file containing the same information but in binary. Here is a sample of the text file:

1
Sex Drive
120 34
6


Here is what I am currently trying
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

struct salle{
int numero; //représente le numéro de la salle.
char film[128]; // représente le nom du film à l’affiche
int places; // représente les places totales de la salle
int placeReservees; // représente les places réservées dans la salle
};

void main(void) 
{
	salle cinema;
	string nomfilm; 
	ifstream texte;
	ofstream bin;
	texte.open("films.txt");
	bin.open("films.bin",ios::binary|ios::out);
	if ((!texte.fail()) && (!bin.fail()))
	{
		texte >> cinema.numero;
		texte.ignore(1);
		getline(texte,nomfilm);
                cinema.film = nomfilm.c_str();
		texte >> cinema.places >> cinema.placeReservees;
		bin.write((char*)&cinema, sizeof(salle));
		while (!texte.eof())
		{
			texte >> cinema.numero;
			texte.ignore(1);
			getline(texte,nomfilm);
                        cinema.film = nomfilm.c_str(); 
			texte >> cinema.places >> cinema.placeReservees;
			bin.write((char*)&cinema, sizeof(salle));
		}
	}
	else 
	{
		cout << "Erreur d'ouverture ou de creation de fichier" << endl;
	}
}


Now I get this error while compiling

cannot convert from 'const char *' to 'char [128]'
There are no conversions to array types, although there are conversions to references or pointers to arrays


Which is related to this:

getline(texte,nomfilm);
cinema.film = nomfilm.c_str()


So I have a problem while trying to convert the string found in the getline to to my char variable, how should I proceed?
You should use strcpy(char*, const char*) function to copy the contents of one char array to another:
strcpy(cinema.film, nomfilm.c_str());

Programmer is responsible to ensure that destination (the 1st parameter) were large enough to take the whole source (2nd parameter).

But what is the reason to mix c-style of char arrays and string class of C++? If cinema.film were of string type as well, the statement
cinema.film = nomfilm;
would perform correct assignment.
thx melkiy il try that asap, sadly I am forced not to change the above struct for this assigment and as such must keep cinema.film as a char.

Il try that strcpy thingy

edit: worked perfectly thx :D
Last edited on
Binary file takes every thing as it exists like if ur putting an integer in binary file it will store in 4 bytes , and if in txt file , it will take each number as one character ,
example
if u store 123456 in binary file than it will take 4 bytes
while if u put it in txt file than it uses 6 characters

<Always keep this in mind while doing binary fileing >
Topic archived. No new replies allowed.