Thread: A Little Rpg
View Single Post
Old 15-09-2005, 10:19 AM   #39
mik
Newbie

 
Join Date: Jan 2005
Location: ,
Posts: 7
Send a message via MSN to mik
Default

So, I don't think that it's a good idea to use "fwrite" here but if you want...

_itoa - convert an integer to a string (see MSDN).
Code for save and load:
Code:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{ 
int age = 15;
int number = 22;
char Fname[12]; //for filename 
cout<<"Enter file to save to: ";

cin.getline(Fname,12); //get data
cout<< endl;

//Open file
FILE *file;
if ((file = fopen (Fname,"w")) != NULL)
{
	char buffer[2];
	_itoa(age, buffer, 10); //convert int to char
	fwrite (buffer,sizeof(char), 2, file);
	_itoa(number, buffer, 10);
	fwrite (buffer,sizeof(char), 2, file);
	fclose(file);
}
else cout<<"Error opening the file";

if ((file = fopen (Fname,"r+t")) != NULL)
{
	char ch_age[2], ch_number[2];
	fread(ch_age, sizeof(char), 2, file);
	fread(ch_number, sizeof(char), 2, file);
	fclose(file);

	age = atoi(ch_age); //convert char to int
	number = atoi(ch_number);
	cout<<"Age = "<<age<<" Number = "<<number;
}
else cout<<"Error opening the file";

cin.get();
return 0;
}
mik is offline                         Send a private message to mik
Reply With Quote