Problem with displaying text (C++)

Started by
3 comments, last by Strings 14 years, 11 months ago
When I run this program it displays a bunch of random characters instead of all +'s. The source is below. #include <iostream> using namespace std; class object{ protected: int x, y; char graphic; public: const int get_x(){return x;}; const int get_y(){return y;}; const char get_graphic(){return graphic;}; void set_x(int new_x){x = new_x;}; void set_y(int new_y){y = new_y;}; void set_graphic(int new_graphic){graphic = new_graphic;}; }; /* There is some bug in here class agent:protected object{ protected: int x, y; char graphic; public: const int get_x(){return x;}; const int get_y(){return y;}; const char get_graphic(){return graphic;}; void set_x(int new_x){x = new_x;}; void set_y(int new_y){y = new_y;}; void set_graphic(int new_graphic){graphic = new_graphic;}; }; */ // ++ create a tile class that allows multiple objects in one tile /* Theoretically I would create an object array or vector and a setting function that looks for an empty cell to jump into */ class tile{ protected: int x, y; object obj; public: const int get_x(){return x;}; const int get_y(){return y;}; const object get_obj(){return obj;}; const char get_contents(){return obj.get_graphic();}; void set_x(int new_x){x = new_x;}; void set_y(int new_y){y = new_y;}; void set_obj(object new_obj){obj = new_obj;}; void set_contents(char new_graphic){obj.set_graphic(new_graphic);}; }; int main(){ cout << "Tiles..." << endl; tile tiles[10][10]; cout << "initalized" << endl; for(int i=0; i >= 10; i++){ //can be optimized for(int j=0; j >= 10; j++){ cout << "populating" << endl; tiles[j].set_x(i); tiles[j].set_y(j); tiles[j].set_contents('+'); } } cout << "Objects..." << endl; object player; cout << "Initializing player" << endl; player.set_x(3); player.set_y(3); player.set_graphic('@'); cout << "Initializing npc" << endl; object npc; npc.set_x(1); npc.set_y(1); npc.set_graphic('N'); cout << "Initializing rock" << endl; object rock; rock.set_x(5); rock.set_y(5); rock.set_graphic('*'); cout << "Output.." << endl; for(int i=0; i <= 10; i++){ for(int j=0; j <= 10; j++){ cout << tiles[j].get_contents(); cout << " "; } cout << "\n"; } }
Advertisement
for(int i=0; i >= 10; i++){ //can be optimized
for(int j=0; j >= 10; j++){

These loops don't run,it should be i<10,j<10.
Thanks. That was the problem.
Also,
for(int i=0; i <= 10; i++){
for(int j=0; j <= 10; j++){
cout << tiles[j].get_contents();
cout << " ";
}

Your tiles array is 10x10 the first elements is 0,0 and the last is 9,9 not 10,10.Again the bounds should be i<10 and j<10.Accesing out of the bounds will cause strange behaviour and crashes.
I realized that when it was outputting extra text.
It's a good thing this matter was addressed before I started writing to the arrays. Thanks again.

This topic is closed to new replies.

Advertisement