Public Group

# Binary io help.

This topic is 4864 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I was wondering how I would go about making a list of names and scores for a highscores list. I have found out how to save the scores, but I don't know how to save the names. Right now I have the names and scores saved as vectors. vector<int> highscores(10, 0); vector<string> highnames(10, "Default"); Is it possible to save whole vectors and load them when starting the game? Thanks in advance.

##### Share on other sites
using your names and structure it could look like this:
#include <iostream>#include <algorithm>#include <vector>#include <string>#include <fstream>using namespace std;int main(void){    vector<int> hiscore;    vector<string> hiname;        {//read score        ifstream hifile("hiscore.lst");        if( hifile)        {        	int score;        	string name;        	while( hifile >> score >> name)        	{        	    hiscore.push_back( score);        	    hiname.push_back( name);        	}        }    }        hiscore.resize( 10, 0);    hiname.resize( 10, "default");        //game goes here    for(int i = 0; i != 10; ++i)   		cout << hiscore << hiname << "\n";        //time to die    {    	ofstream hifile( "hiscore.lst");        if( hifile)        {            for(int i = 0; i != 10; ++i)            	hifile << hiscore << hiname << "\n";        }    }    }

do note that it's highly hackable some encryption scheme or something could be adviceable but if it's just for a single players amusement then if they want to hack the hischore to make themself feel better why not let them....

##### Share on other sites
Just a suggestion here:
Perhaps it is easier to use a structure here for your data. It keeps your data clean and together and is also easily extensible with other fields (for example time before completion etc) without the need for another vector. You could make it like:

struct PlayerData{   string name;   int hiscore;};void main (){   vector<PlayerData> players;   PlayerData pd;   pd.name = "myname";   pd.hiscore = 100;   players.push_back (pd);   if (strcmp (players[0].name, "myname") == 0)

##### Share on other sites
Since the size of your names will vary, and I would doubt you want to manually search for a null character (although, that could be a possiblilty...), you will have to store the length of each name before it is read. Someting like this (I use STL's fstream class):
#include <fstream.h>int highscore_count=10; //Number of highscoresvector<int> highscore(10,0);vector<string> highname(10,"Default");...bool save_highscores() { fstream file("file.dat",ios::out|ios::binary); //Be sure to write the header information! file.write((char*)&highscore_count,sizeof(int)); //Write out each score and the corresponding name for (int i=0;i<highscore_count;i++) {  file.write((char*)&highscore,sizeof(int));  int cur_len=highname.length(); //Tell the length of the name  file.write((char*)&cur_len,sizeof(int));  file.write(highname.c_str(),cur_len); } file.close(); return true;}bool load_highscores() { fstream file("file.dat",ios::in|ios::binary); //Get the number of highscores file.read((char*)&highscore_count,sizeof(int)); //Clear the two vectors and fill them with the data highscore.clear(); highname.clear(); for (int i=0;i<highscore_count;i++) {  highscore.push_back();  file.read((char*)&highscore,sizeof(int));  int cur_len;  file.read((char*)&cur_len,sizeof(int));  //Make a temporary character buffer  char *cur_name=new char[cur_len];  file.read(cur_name,cur_len);  //Set the string  highname.push_back();  highname=cur_name;  delete [] cur_name; //Delete the buffer } file.close(); return true;}

And we say "YAY" if this works.

##### Share on other sites
I've tryed many of these suggestions in many ways, but I must not be doing it right. Sometimes it seems to save the score, but not the name. Some ways it keeps the name if you type it in the same name, but as soon as a different name is entered the other name becomes Default again, but the score stays. Other times theres just an error and it closes. I'm not sure exactly how to save strings, I'm able to save the scores easily.

Before I came here I used:
for (int i = 0; i < 10; ++i)
{
}
Which works for the scores but not the names(strings).

Not sure what I'm doing wrong. :(

##### Share on other sites
ok This should be pretty easy to understand, if you want me to expklain it more cleary or comment it let me know.

ignore my drawing code, i removed alot, left some commented.
scoreboard.h :
#ifndef SCOREBOARD_H#define SCOREBOARD_H#include <string>#include <cstdio>//#include <alfont.h>struct score_element{	std::string name;	int score;        score_element(): name(""), score(0) {}};class scoreboard{private:	score_element highscores[20];	BITMAP *dest;	int offset;	int index;	ALFONT_FONT *hs_font;public:	scoreboard(BITMAP * &dest_);	~scoreboard();	void newscore(int ps);	void draw();};#endif

scoreboard.cpp
#include "scoreboard.h"scoreboard::scoreboard(BITMAP * &dest_): dest(dest_),offset(0),index(18)	{		FILE *fp = fopen("hs.dat","rb");		if(fp == NULL)		{			fp = fopen("hs.dat","wb");									for(int i = 0; i < 20; i++)			{				highscores.name = "cck"; //default name and score				highscores.score = 1000;			}						for(int k = 0; k < 20; k++)			{				int s = highscores[k].name.length() + 1;				fwrite(&s, sizeof(int),1,fp);				fwrite(highscores[k].name.c_str(),s,1,fp);				fwrite(&highscores[k].score,sizeof(int),1,fp);			}			fclose(fp);		}		else		{			for(int k = 0; k < 20; k++)			{				int s;				fread(&s, sizeof(int),1,fp);				char *b = new char[s];				fread(b,s,1,fp);				highscores[k].name = b;				fread(&highscores[k].score,sizeof(int),1,fp);			}			fclose(fp);		}		//hs_font = alfont_load_font("radio.ttf");		//alfont_set_font_size(hs_font, 30);	}scoreboard::~scoreboard()	{		FILE *fp = fopen("hs.dat","wb");		for(int k = 0; k < 20; k++)			{				int s = highscores[k].name.length() + 1;				fwrite(&s, sizeof(int),1,fp);				fwrite(highscores[k].name.c_str(),s,1,fp);				fwrite(&highscores[k].score,sizeof(int),1,fp);			}		fclose(fp);	}void scoreboard::newscore(int ps)	{		int c = 21;		for(int i = 19; i >= 0; i--)		{			if(ps > highscores.score) c = i;		}				if(c < 20)		{                        //either put some code here to get input, or pass a std::string to this function, i call it edittext			highscores[c].name = edittext;			highscores[c].score = ps;		}	}void scoreboard::draw()	{	//Draw your way... /*		BITMAP *line = create_bitmap(400,25);				std::string buf;				for(int j = 0; j < 10; j++)		{			clear_to_color(line,hot_pink);			int ind = index + j;			if(ind > 19) ind =  ind - 20;			char *p = new char[10];			sprintf(p,"%d. %s  %d",(ind + 1),highscores[ind].name.c_str(),highscores[ind].score);			buf = p;			alfont_textout(line, hs_font, buf.c_str(), 0, 0, white);			draw_sprite(dest,line,0, ((j) * 30) - offset);		}		destroy_bitmap(line);		offset++;		if(offset == 30)		{			offset = 0;			index++;		}		if(index == 20) index = 0;*/	}

1. 1
2. 2
3. 3
4. 4
frob
13
5. 5

• 16
• 13
• 20
• 12
• 19
• ### Forum Statistics

• Total Topics
632170
• Total Posts
3004547

×