file loading issue

Started by
2 comments, last by BlueBan007 14 years, 11 months ago
ok so, I am writing my game charachters x position, ypsition, and level to a file and reading it back like so:


#include <iomanip>
#include <fstream>
#include <iostream>

using namespace std;



string content;
int times=0;
int seperator;


void save(){


					 ofstream Save("Save.txt", ios::trunc);
					 Save<<avatarX<<" "<<avatarY<<" "<<screen;
				 
			
}

int GetIntVal(string strConvert){

	int intReturn;

	intReturn=atoi(strConvert.c_str());

	return (intReturn);



}

void load(){

	
	seperator=content.find(" ")+1;
	

	
		

	ifstream load("Save.txt");

	if(load)
	{


		getline(load,content);
		avatarX=GetIntVal(content.substr(0,seperator));
		content.erase(0,seperator);
		avatarY=GetIntVal(content.substr(0,seperator));
		content.erase(0,seperator);
		screen=GetIntVal(content.substr(0,seperator));

	}

	
	Sleep(150);
	
	
}

the x position(the first value) is always loaded accurately, and so does the y value, unless im up gainst the left wall (2d zeldaish game) then the y value is the last 2 digits of the x value! D: ? and the screen value is the last digit of the legitimate y value! D: ? I am totally lost as to why this is happening!
Advertisement
You're only finding the seperator position once, and you're also doing it before you've even read the line in.

Something like this should work.
// Read a line and find the seperator position...getline(load,content);seperator = content.find(' ')+1;// Extract the x-pos and erase...avatarX=GetIntVal(content.substr(0,seperator));content.erase(0,seperator);// Now need to find the next seperators position...seperator = content.find(' ')+1;avatarY=GetIntVal(content.substr(0,seperator));content.erase(0,seperator);// Note there is no space character at the end of the file, so there's// no point trying to extract using it. Just use the whole string.screen=GetIntVal(content));


I'd strongly advise you to write some error handling code - imagine what would happen if your file only had two values in, or if it was empty. You could also look into iterators, which IMHO are a much better way of doing this.

Hope that helps.
thank you!

didnt see it plain before my eyes...after an hour of argg..lol

you are mazing
thank you!

didnt see it plain before my eyes...after an hour of argg..lol

you are mazing

This topic is closed to new replies.

Advertisement