problems with code and a question(still need help!)

Started by
22 comments, last by jakpandora 19 years, 7 months ago
I compiled the following code and got one error:

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;

void player_house(); //Room: the main characters house
void town_square(); //Room: the town square



int main(int argc, char *argv[])
{
  //Declare local variables

  float player_h; //Player health
  float player_g; //The amount of gold the player has
  int player_l; //The amount of lives
  char yn; //choice of yes or no for questions
  char y = 'y'; //Choice of yes
  char n = 'n'; //Choice of no
  char d; //Direction input


  //Declare arrays


  char name[35]; //Player name
  char town[4][15] = {    //Array for town
           {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},
           {16,17,18,19,20,21,22,23,24,25,26,27},
           {28,29,40,41,42,43,44,45,46,47,48,49},
           {50,51,52,53,54,55,56,57,58,59,60,61},
         };




  //Main code

  cout << "Shadow gate - A massive rpg adventure." << endl;
  cout << endl;
  cout << "  *      *     " << endl;
  cout << "  *      *     " << endl;
  cout << "  *      *     " << endl;
  cout << "  *      *     " << endl;
  cout << "  *      *     " << endl;
  cout << "  *      *     " << endl;
  cout << "*****  *****  " << endl;
  cout << "  *      *     " << endl;
  cout << "  *      *    " << endl;
  cout << endl;
  cout << "What be thy name, warrior?" << endl;
  gets(name); //Read the whole array. player types in name
  cout << "I see great potential for you, " << name << " the warrior." << endl;
  cout << "Welcome to Grant Hill village " << name << "." << endl;
  cout << "Do you have any questions?" << endl;
  cin >> yn;
  if (yn == y)
  {
     cout << "I am sure you have many. However, I am not the one to answer them. You should ask people around town. They will know more then I do." << endl;
  }
  if (yn == n)
  {
     cout << "Good. We do not have time for that. If you DO have questions though, you should ask around town." << endl;
  }

  bool done = false;
  do
  {
       cout << "G: " << player_h << endl;
       cout << "Health: " << player_h << endl;
       cout << "Lives: " << player_l << endl;

       if (town[x][y] == 1)
       {
          town_square;
       }
       if (town[x][y] == 2)
       {
          player_house;
       }
   } while (!done);


  system("pause");
  return 0;
}

void Player_house()
{
     cout << "You are in my house!" << endl;
}

void town_square()
{
     cout << "You are in town square!" << endl;
}


I get the following error: 'x' undeclared I dont know why im getting this error. if you look at my code, youl notice on my if statments, I have town[x][y]. I assumed x and y were a and y as in x,y cordinates, but I think the compiler thinks there variables. I am basing my code off of an example some one gave me, so that code might help:

#include <iostream>
using namespace std;

void room_type_1 (int &x, int &y)
{
    char d;
    cout << "you can move in any direction" << endl;
    cout << "which direction do you want to go? (N, S, W, E): ";
    cin >> d;
    if (d == 'n') y --;
    if (d == 's') y ++;
    if (d == 'w') x --;
    if (d == 'e') x ++;
}

void room_type_2 (int &x, int &y)
{
    char d;
    cout << "you can move north and south" << endl;
    cout << "which direction do you want to go? (N, S): ";
    cin >> d;
    if (d == 'n') y --;
    if (d == 's') y ++;
}
        
int main ()
{
    int grid[5][5] = {
        { 1, 1, 1, 1, 1 },
        { 1, 1, 2, 1, 2 },
        { 1, 1, 1, 1, 1 },
        { 1, 1, 2, 1, 2 },
        { 1, 1, 2, 1, 2 }
    };
    int x = 2;
    int y = 3;
    bool done = false;
    do
    {
        cout << "x: " << x << endl;
        cout << "y: " << y << endl;        
        if (grid[x][y] == 1)
            room_type_1 (x, y);
        else if (grid[x][y] == 2)
            room_type_2 (x, y);
    } while (!done);
    return 0;
}


I also have a question. how do I create multiple source files? mainly, I want to have three files. main.cpp, battle.cpp, and resource.cpp main is all the main code. however, in battle and resource, I basically just want to use the code I make in them as a function in the other. so what I mean is that, I write the battle code in battle.cpp, but then just type something and get that code executed in main.cpp I dont know if that makes sense or not. I hope someone can help with my two problems. thanks! [Edited by - jakpandora on September 16, 2004 2:51:24 PM]
______________________________My website: Quest Networks
Advertisement
Actually, you haven't declared x as a variable anywhere. You've also declared y to be a char and set it equal to 'y'. So when the compiler tries to compile this line:

town[x][y]

it turns it into:

town[undeclared]['y']

You should start by getting rid of the y and n char variables. It's readable enough to use:

if(yn == 'y')

Next you should declare x and y variables, possibly as int variables, and you have to set them to a valid number before you use them as indexes into an array.

I also noticed that you declare "player_house()" at the top of the file but called it "Player_house()" at the bottom. C/C++ is case-sensitive, so it sees those as two different functions.

You may have other errors in there as well, but I have to run.

Hey jakpandora,
this is cool that you are making a text adventure! Anyway I had a look and this is what i came up with:

1.The code question.
ok i changed a few things.
Firstly i ripped out

char y = 'y'; //Choice of yes
char n = 'n'; //Choice of no

because you can test for these on the fly, like so

if (yn == 'y')
{
cout << "I am sure you have many. However, I am not the one to answer them. You should ask people around town. They will know more then I do." << endl;
}

this now means you are free to make the variables

int x, y;

for the town location because thet were undeclared before.

I also added some numbers into your variable for player_gold, player_health etc...Then I got the player to input some cordinates (so you can test the town_square function).

ok here is the code I came up with

//////////////////////////////////////////////////////////////

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cmath>

using namespace std;

void player_house(); //Room: the main characters house
void town_square(); //Room: the town square



int main()
{
//Declare local variables

float player_h = 100.0f; //Player health
float player_g = 100.0f; //The amount of gold the player has
int player_l = 5; //The amount of lives
char yn; //choice of yes or no for questions
char d; //Direction input

int x=0 ,y=0;

//Declare arrays


char name[35]; //Player name
char town[4][15] = { //Array for town
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},
{16,17,18,19,20,21,22,23,24,25,26,27},
{28,29,40,41,42,43,44,45,46,47,48,49},
{50,51,52,53,54,55,56,57,58,59,60,61},
};




//Main code

cout << "Shadow gate - A massive rpg adventure." << endl;
cout << endl;
cout << " * * " << endl;
cout << " * * " << endl;
cout << " * * " << endl;
cout << " * * " << endl;
cout << " * * " << endl;
cout << " * * " << endl;
cout << "***** ***** " << endl;
cout << " * * " << endl;
cout << " * * " << endl;
cout << endl;
cout << "What be thy name, warrior?" << endl;
gets(name); //Read the whole array. player types in name
cout << "I see great potential for you, " << name << " the warrior." << endl;
cout << "Welcome to Grant Hill village " << name << "." << endl;
cout << "Do you have any questions?" << endl;
cin >> yn;
if (yn == 'y')
{
cout << "I am sure you have many. However, I am not the one to answer them. You should ask people around town. They will know more then I do." << endl;
}
if (yn == 'n')
{
cout << "Good. We do not have time for that. If you DO have questions though, you should ask around town." << endl;
}

bool done = false;
do
{
cout << "G: " << player_h << endl;
cout << "Health: " << player_h << endl;
cout << "Lives: " << player_l << endl;

cout<<"Please enter your location: x y (separated by a space)\n";
cin>>x>>y;

if (town[x][y] == 1)
{
town_square();
}
if (town[x][y] == 2)
{
player_house();
}
} while (!done);


system("pause");
return 0;
}

void player_house()
{
cout << "You are in my house!" << endl;
}

void town_square()
{
cout << "You are in town square!" << endl;
}

////////////////////////////////////////////////////////////

the player house function definition also had a capital letter on the 'P' so i changed it to lowercase.

If you need me to explain the code further please ask :) Anyway hope this helps

-onehundred

thanks guys. the part where I typed player_house wrong was actually just a typo. as for the town[x][y] thing, I didnt think they were supposed to be declared as any type of variable. I tthought they were regular x,y cordinates within the array. also, thank you for fixing my code, and for being so freindly. ratings for you and s_p_oniel(sorry if I spelled that wrong)
______________________________My website: Quest Networks
Thats cool man :) Lemme know how it turns out!

-onehundred
hey, onehundered, there seems to be a problem with your code. when I compiled it, it ran perfectly up until I entered where I wanted to go in x and y. when it got there, it just asked "Please enter your location: x y (separated by a space)" forever. any help on this? also, why do you have a .of after the money and health variables. what does that do?
______________________________My website: Quest Networks
The code inside the do while loop will execute forever, because the bool variable done has no way to be set to true. It looks like that block of code is your main game loop, which will run over and over again, until the game stops by setting done to true.

Try entering 0 0 when it asks for x and y. That should trigger the town_square function.

The float variables don't have .of after them. They have .0f, as in dot zero eff. Entering an integer value (without a .) may trigger a warning because you're trying to assign an int to a float. This is technically ok, but the compiler will warn you that you might be making a mistake. If you add use a decimal when specifying decimal values, the compiler reads it as a double type, which is also a floating point number. This might also cause a warning. The only way to be absolutely specific about a true float number is to always use a decimal, and add the character f after the number. Then the compiler knows you really meant to use a floating point type.

float a = 5; // Warning. assigning int to floatfloat b = 5.0 // Warning. assigning double to floatfloat c = 5.0f // OK!
1) C++ has no concept of a "coordinate". Yes, you are using a 2-dimensional array to represent a "grid of locations", but you can use it to represent a gazillion other things as well.

Remember, also, that there is absolutely nothing magic about any possible legal variable (identifier, in the general case) name (except those reserved for use by the implementation).

2) Even if it did, umm... where do you want the player to start out? So you would have to specify the x and y anyway.

Notice your sample code declares variables x and y, and initializes them, in the main loop. Within the functions, x and y are provided as parameters (in this case, passed by non-const reference), so they are available there as well.

3) You need () after 'player_house' and 'town_square' in order to actually call the function. C++ allows expressions as statements, which is what you have without the (). It's like saying "The player_house function.". This sentence no verb. Guh.

4) Perhaps you don't want to output the player's health twice with different labels, I suspect the first one is a typo for player_g.

And again with the variable initialization. What exactly do you expect the player's gold, health and lives to be, given that you never set them?

5) In the provided code, it is ".0f", not ".of". This is good practice for emphasizing that you have a floating-point value.

When you write a constant (i.e. not a variable name or function call or keyword or punctuation, etc...), the compiler has to figure out what kind of thing it is. A plain old set of digits 0-9 (with possibly a negative sign at the front) gets interpreted as an integer by default; adding a decimal fraction forces it to be a floating-point value, which is normally of type double. Adding an 'f' on the end of that forces type float, instead of double.

In this case, there is no real difference; since you are assigning to a float-typed variable, you will have a float-typed value there. If you assign an integer to a float variable, it will get implicitly converted for you. Implicit conversion can be problematic in the general case, though (it can lose information, and sometimes it doesn't work the way you expect). Also, the conversion takes a couple extra instructions (although it is probably not worth worrying about, and when you are using a *constant*, this is easily optimized away).

6) The provided code will loop infinitely if you don't input in the format it expects, because it lacks error checking. Welcome to the first major surprise/annoyance of working with cin. What happens is:

- cin sees invalid input (something other than a number followed by a space followed by a number). Even if that's what you typed this time around, there could have been stuff left around from the last time you were asked for input.

- Since input is invalid, it stops trying to read data, sets a "fail bit" internally, and *does not advance in the stream*. Therefore, the invalid data is still at the front.

- The code loops around as it normally would, and tries to cout and cin again. This time, the buffer already has input in it (the stuff you typed last time), so you don't even get a chance to type a response. Cin tries to read the same thing again, and fails again. Actually, I'm not even sure it gets that far; now that I think about it, it's probably just going to skip right through because the fail bit is already set.

The tools you need to deal with this are:

1) This idiom:

if (cin >> foo >> bar) {
// read was successful
} else {
// read failed
}

The standard library implements deep magic to make this work, that you probably shouldn't try to understand right now.

2) cin.reset(), will clear the fail bit if it is set.

3) cin.ignore(int max_distance, char until) will skip over (presumably bad) input up to a maximum distance of max_distance, or until it finds the 'until' char.
yeah with a float variable you are suppose to write
float myVariable = 0.0f

just one of those weird assignment things really :)

The reason for the foreverness is that you've got a loop going on with no escape sequence. So here i have added one: The code should say "Press any key" after you visit the town
Also i tidied up the test a bit.

//////////////////////////////////////////////////////////////#include <stdio.h>#include <iostream>#include <fstream>#include <string>#include <cstdlib>#include <cmath>using namespace std;void player_house(); //Room: the main characters housevoid town_square(); //Room: the town squareint main(){//Declare local variablesfloat player_h = 100.0f; //Player healthfloat player_g = 100.0f; //The amount of gold the player hasint player_l = 5; //The amount of liveschar yn; //choice of yes or no for questionschar d; //Direction inputint x=0 ,y=0;//Declare arrayschar name[35]; //Player namechar town[4][15] = { //Array for town{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},{16,17,18,19,20,21,22,23,24,25,26,27},{28,29,40,41,42,43,44,45,46,47,48,49},{50,51,52,53,54,55,56,57,58,59,60,61},};//Main codecout << "Shadow gate - A massive rpg adventure." << endl;cout << endl;cout << " * * " << endl;cout << " * * " << endl;cout << " * * " << endl;cout << " * * " << endl;cout << " * * " << endl;cout << " * * " << endl;cout << "***** ***** " << endl;cout << " * * " << endl;cout << " * * " << endl;cout << endl;cout << "What be thy name, warrior?" << endl;gets(name); //Read the whole array. player types in namecout << "I see great potential for you, " << name << " the warrior." << endl;cout << "Welcome to Grant Hill village " << name << "." << endl;cout << "\nDo you have any questions?" << endl;cin >> yn;if (yn == 'y'){cout << "I am sure you have many. However, I am not the one to answer them. You should ask people around town. They will know more then I do." << endl;}if (yn == 'n'){cout << "\nGood. We do not have time for that. If you DO have questions though, you should ask around town." << endl;}bool done = false;do{cout<<"\n\n";cout << "G: " << player_h << endl;cout << "Health: " << player_h << endl;cout << "Lives: " << player_l << endl;cout<<"Please enter your location: x y (separated by a space)\n";cin>>x>>y;if (town[x][y] == 1){town_square();done=true;   // *LOOP EXIT STATEMENT* one this code block runs the loop will exit}if (town[x][y] == 2){player_house();done=true;	// *LOOP EXIT STATEMENT* one this code block runs the loop will exit}} while (!done);system("pause");return 0;}void player_house(){cout << "\nYou are in my house!\n" << endl;}void town_square(){cout << "\nYou are in town square!\n" << endl;}


Tell me if there is anything that looks a little exotic :)



thanks guys. I dont know where I would be without you.(just curious, Do I appear to be "slow" at programming? as in, do most people learn better and faster then I have? I have been learning for a little over a month and a half. just wondering.)
______________________________My website: Quest Networks

This topic is closed to new replies.

Advertisement