Binary io help.

Started by
5 comments, last by Zahlman 18 years, 12 months ago
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.
Advertisement
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....
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
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)


I assume you know the rest already, otherwise please ask.

Crafter 2D: the open source 2D game framework

?Github: https://github.com/crafter2d/crafter2d
Twitter: [twitter]crafter_2d[/twitter]

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.
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire
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)
{
fin.read((char *)(&highscores), sizeof(highscores));
fin.read((char *)(&highnames), sizeof(highnames));
}
Which works for the scores but not the names(strings).

Not sure what I'm doing wrong. :(
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;<br>				fread(b,s,<span class="cpp-number">1</span>,fp);<br>				highscores[k].name = b;<br>				fread(&amp;highscores[k].score,<span class="cpp-keyword">sizeof</span>(<span class="cpp-keyword">int</span>),<span class="cpp-number">1</span>,fp);<br>			}<br>			fclose(fp);<br>		}<br><br>		<span class="cpp-comment">//hs_font = alfont_load_font("radio.ttf");</span><br>		<span class="cpp-comment">//alfont_set_font_size(hs_font, 30);</span><br>	}<br><br>scoreboard::~scoreboard()<br>	{<br>		FILE *fp = fopen(<span class="cpp-literal">"hs.dat"</span>,<span class="cpp-literal">"wb"</span>);<br>		<span class="cpp-keyword">for</span>(<span class="cpp-keyword">int</span> k = <span class="cpp-number">0</span>; k &lt; <span class="cpp-number">20</span>; k++)<br>			{<br>				<span class="cpp-keyword">int</span> s = highscores[k].name.length() + <span class="cpp-number">1</span>;<br>				fwrite(&amp;s, <span class="cpp-keyword">sizeof</span>(<span class="cpp-keyword">int</span>),<span class="cpp-number">1</span>,fp);<br>				fwrite(highscores[k].name.c_str(),s,<span class="cpp-number">1</span>,fp);<br>				fwrite(&amp;highscores[k].score,<span class="cpp-keyword">sizeof</span>(<span class="cpp-keyword">int</span>),<span class="cpp-number">1</span>,fp);<br>			}<br>		fclose(fp);<br>	}<br><br><span class="cpp-keyword">void</span> scoreboard::newscore(<span class="cpp-keyword">int</span> ps)<br>	{<br>		<span class="cpp-keyword">int</span> c = <span class="cpp-number">21</span>;<br>		<span class="cpp-keyword">for</span>(<span class="cpp-keyword">int</span> i = <span class="cpp-number">19</span>; i &gt;= <span class="cpp-number">0</span>; i–)<br>		{<br>			<span class="cpp-keyword">if</span>(ps &gt; highscores<span style="font-weight:bold;">.score) c = i;<br>		}<br><br>		<br>		<span class="cpp-keyword">if</span>(c &lt; <span class="cpp-number">20</span>)<br>		{<br>                        <span class="cpp-comment">//either put some code here to get input, or pass a std::string to this function, i call it edittext</span><br>			highscores[c].name = edittext;<br>			highscores[c].score = ps;<br>		}<br>	}<br><br><span class="cpp-keyword">void</span> scoreboard::draw()<br>	{	<br><span class="cpp-comment">//Draw your way… <span class="cpp-comment">/*<br>		BITMAP *line = create_bitmap(400,25);<br><br>		<br>		std::string buf;<br>		<br>		for(int j = 0; j &lt; 10; j++)<br>		{<br>			clear_to_color(line,hot_pink);<br>			int ind = index + j;<br>			if(ind &gt; 19) ind =  ind - 20;<br><br>			char *p = new char[10];<br>			sprintf(p,"%d. %s  %d",(ind + 1),highscores[ind].name.c_str(),highscores[ind].score);<br>			buf = p;<br>			alfont_textout(line, hs_font, buf.c_str(), 0, 0, white);<br>			draw_sprite(dest,line,0, ((j) * 30) - offset);<br>		}<br><br>		destroy_bitmap(line);<br><br>		offset++;<br>		if(offset == 30)<br>		{<br>			offset = 0;<br>			index++;<br>		}<br>		if(index == 20) index = 0;*/</span><br>	}<br><br><br><br><br><br><br><br></pre></div><!–ENDSCRIPT–> 
Seems like I've been linking this a lot recently...

This topic is closed to new replies.

Advertisement