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

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

## Recommended Posts

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 << 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]

##### Share on other sites
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.

##### Share on other sites
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 << 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;

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

##### Share on other sites
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)

##### Share on other sites
Thats cool man :) Lemme know how it turns out!

-onehundred

##### Share on other sites
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?

##### Share on other sites
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!

##### Share on other sites
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) {
} else {
}

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.

##### Share on other sites
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 :)

##### Share on other sites
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.)

##### Share on other sites
From what I've seen, your way of thinking about things is going to make learning C++ difficult, but if you pay attention to the reasoning behind my (our) corrections, you should catch on quickly.

Also, since I'm thinking I really should write an article (or even a full tutorial) some day, you're helping me think about where to begin, which is always the hardest part ;)

But seriously, don't worry about how much you know about programming until at least the one-year mark. And at that point, it's time for a reality check; you have another nine years or so to go.

##### Share on other sites
ok, thanks zalhman. I just seem to see articles about people all the time with headings like "person becomes genius programmer in 2 weeks" and it just seems like everyones like that. I;m actually suprised I'm even this far. ya, I know my way of thinking is weird, but so is the book i;m still using, so hopefully once I finally get that book ive been saving for, ill do better.

also, I encourtered a run time error in my updated code. for some reason, when it gets to the function and the parts where you enter x, and y, it just instantly says im at the house, and it ends. why does it do this? also, I was told I need to have a starting location for my character. perhaps this is why the error is caused, but I dont know how to fix it. any help?

##### Share on other sites
come one guys! my updated code is that of onehundreds(his last post)

##### Share on other sites
come on! why wont anyone reply!

##### Share on other sites
Quote:
 Original post by jakpandoraalso, I encourtered a run time error in my updated code. for some reason, when it gets to the function and the parts where you enter x, and y, it just instantly says im at the house, and it ends. why does it do this? also, I was told I need to have a starting location for my character. perhaps this is why the error is caused, but I dont know how to fix it. any help?

What are you inputting for x and y?
Does the problem happen with all kinds of input?
Or are you saying that it prompts you for input and before you can enter it the program ends?

From eyeballing the code it looks like....
If you enter 0 space 0 then you go to townSquare()
If you enter 0 space 1 then you got to playerHouse()
Any other input results in repeating the loop.

##### Share on other sites
the problem is that it doenst let me input anything at all. it just says you are at town square, and the program ends. any help?

##### Share on other sites
i think your program is ending when you get to the house because thats what your telling it to do (that sounded dumb, but honestly, its true!)

lets go through a bit of the code by hand:

do...//three full stops indicating there is code here, but is unimportant.if (town[x][y] == 2){player_house();done=true;	// *LOOP EXIT STATEMENT* one this code block runs the loop will exit}...while (!done);...//below is the function that you call.void player_house(){cout << "\nYou are in my house!\n" << endl;}

first of all you test for the coordinates, (ignoring the problem with instantly being at the house), if the player is at the house, you call player_house().
in player_house(), you display the desired text. the program then goes back up to where you called the function.
after this it sets 'done' to true.
it continues past the 'if' statements and gets to the (while!done)
the problem being that you just set 'done' to true, so it will exit the do while loop.

I was wondering, do you start immediately at the house or the square. because youve set x and y to 0, and the loacation in your array at 0,0 holds a '1' (town[0][0]) so it should say that you are in the square. if it doesnt than i have no idea why this is happening.

EDIT: just seen your last post. yes this is correct. you set xand y to zero when you initialise them, so it will check the array at town[0][0]. this location in the array holds a '1'. when you get to the 'if' statements, it says "if the integer in loacation 0,0 in the town array holds a '1', call town_square()"

##### Share on other sites
ok, I think I get that. ill fix the code and see if it works. thanks.

##### Share on other sites
Ok I know what the problem is.
When the guy asks "Do you have any questions?" I'll bet you are answering "yes" or "no" instead of "y" or "n". You only left room for a one character answer (ie char yn;). The rest of the word "yes" or "no" is still in the buffer when you try to input x and y. That is screwing up your input and your program is using the value you initialized x and y as at the top of your program (ie 0 and 0) which would always take you to the town square and end your loop.

Try answering the question with a 'y' or 'n'.

##### Share on other sites
actually, I did change it to a 'y' and 'n' a while ago. the problem is still happening. I still dont know why it wont let me give any input...

##### Share on other sites
I don't see what the problem is here. I copied and pasted onehundred's code from his last post, and it works fine for me. Are you sure you haven't changed anything?

##### Share on other sites
im sure. ill try one last time to see if it wroks though.

*EDIT* I cut and pasted his code directly. I still get the same problem. it wont let me input anything. it just says im in town square and the program ends. I am using dev c++ 4 if it makes a differance.

##### Share on other sites
Quote:
 Original post by jakpandoraim sure. ill try one last time to see if it wroks though.*EDIT* I cut and pasted his code directly. I still get the same problem. it wont let me input anything. it just says im in town square and the program ends. I am using dev c++ 4 if it makes a differance.

You == weird.

Try a new workspace, or something.
I'm using Visual C++ (6.0), but thereotically it should make a difference...

##### Share on other sites
um, so your saying im weird because my code wont compile correctly? ok, your no help. I already tried a new workspace in dev. didnt work. I am not even going to try with msvc 6.0, because it isnt noob freindly. ill just try to figure out something. thanks for everyones help.

##### Share on other sites

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

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628676
• Total Posts
2984172

• 13
• 12
• 9
• 10
• 9