Game Programming and Development Tools

Help me learn C++ – bwoogie

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok, so im on my quest to learn c++. But i've run into a strange problem. this code runs ok without any problems. except after the first input it quits. i have no idea why. it prints the next line, you can see it right before the window closes but even though there is a cin.get() it wont wait for user input.. o_O


#include <iostream>
using namespace std;

int main()
{
char yourname;
int age;
cout<<"First C++ Program... That does nothing cool.\n";
cout<<"Go ahead and enter your name. ";
cin>> yourname;
cout<<"Your name is " << yourname << ", huh? hmm..\n";
cout<<"So, how old are you, "<< yourname <<"? ";
cin>> age;
cin.ignore();

cout<<"You are "<< age << " years old, eh? ";
if (age > 21)
{
cout<<"That's gettin pretty old\n";
}
else
{
cout<<"C++ for little people!!!\n";
}

cin.get();

}

EDIT: ok, i have just learned something. char only excepts one character, am i right? because if i enter only 1 letter for yourname then it works. i'm pretty sure i tried that before i posted on here and it didnt work... i think it was having a problem building the new exe.

So, what do they call a string in c++?

------------------
~~~boogie woogie woogie~~~

[This message has been edited by bwoogie (edited January 23, 2007).]

[This message has been edited by bwoogie (edited January 23, 2007).]

[This message has been edited by bwoogie (edited January 23, 2007).]

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
in c and c++, a string is an array of characters or char[]. there IS a string wrapper class in the standard library but i'd suggest getting to know character arrays before moving on to them

EDIT: oh yeah, forgot to say that all strings are terminated with a '\0' character (null character). thats how the compiler knows that the string is ending (otherwise it would assume that it continues past just your text).

[This message has been edited by jestermax (edited January 23, 2007).]

steve_ancell

Member

Posts: 37
From: Brighton, East Sussex, Southern England, United Kingdom.
Registered: 09-16-2006
Look on the brightside Bro... You seem to know a lot more C++ than me. I can understand some of it, but not enough yet to start programming with it. That's why I took the easy way, Blitz3D to the rescue.

------------------
It's nice to be important, but it's more important to be nice !

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
quote:
Originally posted by jestermax:
in c and c++, a string is an array of characters or char[]. there IS a string wrapper class in the standard library but i'd suggest getting to know character arrays before moving on to them

ok! thanks. so, is there a way to allow it to have an unlimited length?

------------------
~~~boogie woogie woogie~~~

Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
Steve: I started there, and are moving up, kinda.

bwoogie: I've been doing C++ a total of 3 days now, so beware. You forgot cin.ignore after "Cin >> yourname". Not much else I can say though.

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
mene, i didnt realize that i needed to do that after a char as well. i thought that it just stripped unwanted characters from integers.

------------------
~~~boogie woogie woogie~~~

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by bwoogie:
ok! thanks. so, is there a way to allow it to have an unlimited length?


A char array is always going to point to some fixed amount of memory on the heap or the stack.

The std::string object is the easiest way to get an unlimited string for inputs.

Make sure to have this line near the top:
#include <string>

create it like this:
string yourname;

read in a single word like this:
cin>>yourname;

or read in a line like this:
getline(cin, yourname);

------------------
+---------+
|steveth45|
+---------+

Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
I'm pretty sure it takes everything. I mean, its an interger, and its taking enter.

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
Strange as it may seem, strings are one of the most controversial types in C/C++. If you don't believe me take a look at this substantial article showing all the differences.

If you are wanting to learn c++ and not c per se, stick with the "string" type and don't forget #include <string>

Check out this tutorial for more details.

EDIT: Nice synopsis steveth

------------------
Sam Washburn

[This message has been edited by samw3 (edited January 23, 2007).]

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
Steveth, thanks alot for that. now, one more question. it doesnt seem to accept spaces. the program just quits.

------------------
~~~boogie woogie woogie~~~

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
if memory serves me, the "<<" operator delimits spaces. which means you can't have spaces in your input.

theres actually no "real" way to have an unlimited length string. it SEEMS that way, but behind the scenes the string works like a vector object (which you'll get into later so don't worry about it).

as samw3 brought up, you'll probably want to stick to strings while you're learning c++. i won't jump ahead any more then i did. *zips mouth*

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
hey, i am a big fan of char arrays i just don't see why one would need to make a simple concept such as a string into a class ,it add a huge amount of incompatibility to previously written codes(specially c codes).

as for you problem bwoogie , i don't want to make things more complicated than they are to you but in stream i/o (which i don't like to use),there is lots of problem with getting just one char from the keyboard because you really are reading from a stream buffer not the keyboard.

some programs include the header file #include<conio.h> and put the getch() function at the end of the code, then it will work just fine or include #include<stdlib.h> and put system(PAUSE) (i haven't used this one).


and to explain to you what arrays are incase you don't know they are just a way of grouping similar data types.

so as you noted char holds just one character but a character array of 32 chars holds 32 characters hence a string. and when you declare a c style string you do it like char x[33]; as you see i made it 33 instead of 32 because we need an extra place for the end-of-string character which is '\0' that's how you compiler could tell that it reached the end of your string other wise you would be seeing gibberish stuff at the end of your string.

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok, what does everyone suggest i learn now?
i understand if's, and loops, and stuff like that.. your basic stuff found in any language... but what should i tackle next that's important to any c++ programmers knowledge?

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
I would say functions and pointers.

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
i know the basics of functions... i think....

int functions return integers
void returns nothing
ect.
right?

pointers? i fear pointers... i know they are supposed to be fairly easy to understand but the people who tried to teach me before on another board didnt do a very good job... haha.

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
Do you understand arrays? Pointers are like a super-flexible version of an array element. In fact, in c/c++ an array is a pointer.

Here's a quick run through. Arrays have an index right? a[10] = 5; 10 is the index. 5 is the value.

Now, imagine you have an array that is the size of your entire computer's memory, then the index would be the actual memory location of the value.

now with arrays we can use a variable to reference an index like this:

int i = 10;
a[i] = 5;

pointers allow us to assign the *memory location* of a variable to another variable, just like an index.

So here goes the quick run through

int *i; // the asterisk(*) defines i as a pointer to an int
int j = 5; // a regular variable
i = &j; // the ampersand(&) means take the address(index) of j, not the value and assign it to i;
cout << *i; //Prints the value that is found at whatever address i is pointing to which in this case is 5 since its location is the same as j's

I can answer more questions in the morning as I'm going to bed. So I bid thee all good night.

------------------
Sam Washburn

[This message has been edited by samw3 (edited January 23, 2007).]

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
quick note (Zero Cool/samw3 seems to be doing a good job here):when you declare a null pointer, always set it to 0, not null.
int* ptr = 0;
just a "best practice"
bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok, thanks for the refresher. i remember learning about that. but i still dont really understand why... why would you want an "array" the size of your computer's memory... and couldn't that also cause problems (i guess it doesnt because it seems everyone who uses c++ uses pointers) since everyone's computer has a different amount of RAM.

ok i think i know what my problem is. i just don't know when/why you would use it so that's keeping me from understanding it.

i think im going to bed now too. see you guys after work.

------------------
~~~boogie woogie woogie~~~

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by bwoogie:
Steveth, thanks alot for that. now, one more question. it doesnt seem to accept spaces. the program just quits.

First of all, use getline for any input that has spaces in it.

Make sure you put a cin.ignore() after every cin>> command. If you don't, a following getline command will not wait for input, but deliver an empty string.

------------------
+---------+
|steveth45|
+---------+

[This message has been edited by steveth45 (edited January 24, 2007).]

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
Here is a common use for pointers -- Passing a parameter by reference

// Non reference version
void doSomething(int i){
++i;
}
int x = 5;
doSomething(x)

Upon executing the doSomething function above, it copies x into i and then performs the function. When the function is finished x still equals 5.

// Reference Version
void doSomething(int *i){
*i++;
}
int x = 5;
doSomething(&x)

Upon executing this function however, i is defined as a pointer to an int, not as an int. So, &x passes the memory address of x into the function and assigns it to the i pointer.

Inside the function, the value located at i's address is incremented. So, when the function returns x equals 6 since i pointed to x's address.

There are two reasons why to do this that I can think of.

1. if you are passing a massive struct as a parameter, skipping that copy to local variable is obviously faster.

2. If you need to "return" more than one value from the function you can pass parameters that you want modified by reference. For example:

int doSomething(int x, int y) // this can only return one int. i.e. return 5;

void doSomething(int *x, int *y, int *z) // this can "return" three values by modifying x, y, and z's values in the function, though you really don't use the return keyword to do it.

That's just one example of using pointers. Another is the very flexible collection structure "link list".

Some people think pointers are evil. Since they reference memory locations directly, you can accidentally write to improper areas of memory and wreak havoc. This is how buffer overrun security exploits occur.

So, have fun with pointers, but just don't run with scissors.

------------------
Sam Washburn

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
initializing a pointer to 0 isn't setting it to be your computer's memory. it's still a null pointer and the compiler treats it that way. man, i'm EXTREMELY rusty now
Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
Not sure what to add except there's some great tutorials on pointers, ext. on cprogramming.com

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
Pointers could get really confusing if you don't understand the concept behind them.

and the largest amount of int arrays you can have as far as i know is 2gb
so if your ram is larger than that you are out of luck and even if you wanted to unless you use a 64bit system the largest amounts of objects that an array can have is 2gb(in integer terms something like 2 or 1 billion).

and you rarely see a program that doesn't use a pointer so,make sure you really understand them before you move on to classes and dynamic memory allocation.

btw, hackers can use pointers in stack cracking,which has been a great source of trouble in the security community.

and something you should know,c++ pointers and memory allocation stuff is something you should really master, even the pro's mess up with that,for example the great american black-out of 2003,that caused black outs through many states and toronto and some canadian cities,was caused by a faulty c++ memory leak, and the mars rover was lost in mars for a couple of weeks because of memory allocation problems.


------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
pointers also were the cause of Atilla the Hun's raiding parties poor chap never understood void pointers...
SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
quote:
Originally posted by spade89:
hey, i am a big fan of char arrays i just don't see why one would need to make a simple concept such as a string into a class ,it add a huge amount of incompatibility to previously written codes(specially c codes).

Because a class makes things even easier. And as you get familiar with both, you will begin to see the complexities, problems, and difficulties in maintaining and using char arrays.

Understanding and becoming familiar with collection classes will make coding in any object oriented language much easier. The classes take care of management and length issues making you, the developer, more productive.

char arrays are not very dynamic and are much more prone to memory issues. I don't know if you have ever run into really strange crashes before. Crashing at random locations each time you run. Sometimes crashing, sometimes not. Crash only happens in Release version. I have found the NUMBER ONE reason for these random crashes is due to array bounding issues. And, more specifically, it is code using char arrays and going beyond the array boundary.

These issues are extremely tough to track down. It is often due to using strcpy and copying a larger string into a small string. Sure, you can use strncpy to protect this, but then you have the added overhead of being sure to add the NULL terminator yourself. What if you forget? Why even have that extra step? And it's just not very clean.

Concatening a 'string' is much easier than concatenating char arrays. What if you concatenate beyond the size? How about reallocating space for a char array?

char arrays will work and serve their purpose, but using an OO class is much easier and simpler to use for the developer.

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
i use char arrays for static strings. things that you set once and never change. the string object is very handy to have and i use it most of the time. oh yeah, opposite side: if you have limited space or you have to send the text via socket, etc you don't really want to send the whole wrapper object, you'll just want to send text (aka char array)
Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
I don't understand "Void".

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
void means "nothing" or "null"
if a function has a void return type then that means it doesn't return anything.
samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
heh heh. true, but then why is it a void pointer can store an address to anything? C can be confusing at times.

------------------
Sam Washburn

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
because void pointers are the exception and are a blast
bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
I get it!!!! .... i think..... haha

so basically pointers are so you can play with the same data without actually copying the data to another variable?

they point to the address where the data is stored so you can edit the data in another function where the original variable doesn't exist.

------------------
~~~boogie woogie woogie~~~

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by samw3:

// Reference Version
void doSomething(int *i){
*i++;
}
int x = 5;
doSomething(&x)



Actually, that's the "Pointer Version", this is the reference version:

void doSomething(int &i){
i++;
}
int x = 5;
doSomething(x)

References work similar to pointers, but instead of having to dereference the pointer, the reference just acts like a normal variable and can be incremented by calling "i++". Also, notice that you pass in the variable directly, without having to extract the address: "doSomething(x)".

References are similar to pointers, but the syntax is easier, and it is more efficient because it doesn't have to waste time dereferencing a pointer. Also, they are safer because you can't use them accidentally to address the wrong memory location.

------------------
+---------+
|steveth45|
+---------+

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
hey for those of you learning c++,my advice to you before you move on to oop,templates or other stuff is that you first get aquainted with how things work in c++,like make a calculator that accepts input in the form of 1+2*3
and displays the output,or make a program to ilusstrate fibonacci number.

or try playing around with pointers a bit.

and don't forget "Practice makes perfect.".plus practice lets your brain adjust to the new grammer of the language.

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
yes what he said .... don't even think about all the object-oriented goodness you'll be missing out on
samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
You are correct steveth. My point was to really try and showcase pointers in that snippit. Although it is good to know how to pass a variable in as a pointer(*) or with a reference(&).

I also think its wise to really get your head around dereferencing pointers especially since you will probably have to deal with handles (pointers to pointers int **i) sometime in the future.

But still, thanks for the correction.

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
quote:
Originally posted by spade89:
hey for those of you learning c++,my advice to you before you move on to oop,templates or other stuff is that you first get aquainted with how things work in c++,like make a calculator that accepts input in the form of 1+2*3
and displays the output,or make a program to ilusstrate fibonacci number.

Ok good idea. I'm working on a calculator right now.

------------------
~~~boogie woogie woogie~~~

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
One thing I would recommend, is to actually write out code in a notebook. This way you learn some very very important skills with programming. I have 3 notebooks filled with my programming ideas and the like. You'll find you'll check your code that your writing in your head and hopefully pick up on more errors then you would have thought. It also allows you to do sketches and draw out ideas, or even diagrams, in the easiest way.

Plus you don't have intellisence or the like (evil Visual Assist) to help complete your words or show the data structure, which over times makes you think more about your program (such as data structures, variable names, function names and parameters, etc.).

Final major bonus, you will over time be able to code pretty much anywhere! As long as you have some paper and a pen you'll be set (which you should definately get!!). You need a small pad (quarter of an A4, so I think an A6...), and a nice big A4 notebook the A4 200 page notebooks are the ones I like to get. I used to work on projects while I was catching the train to Uni. I had just over an hour trip and I was able to get a lot of work done

------------------
www.auran.com

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
YES do that! i started doing that when i first programmed and i can code better on paper then 90% of my ex-classmates could on a computer. don't rely on compile-check-compile methods to solve all your coding issues.
bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
you're right about not using stuff like intellisense so you learn how to use functions and such and not just rely on it doing the hard work for you. i have to admit though, it is a lifesaver at times. i do need to get me a notebook some time...

------------------
~~~boogie woogie woogie~~~

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by dartsman:
One thing I would recommend, is to actually write out code in a notebook.

Yeah, it's a great way to program without a computer around. No, seriously, sketching your ideas ahead of time, planning data structures and interrelationships is very helpful to do on paper before you fire up the IDE. I have a notepad and some graph paper at my desk at work, and my ideas usually take some form on paper before I hit the keyboard.

Intellisense is great, so what if you don't remember if the variable is named numThis or numThat, you hit the period and type "nu" and hit enter. This is called productivity. Maybe you think variable declarations are numbing our programmer minds and we should deal strictly with memory locations in hex and write all our code in ASM. ASM, however, is a layer of abstraction between you and the cpu, why not code directly in hex by memorizing the hex values for all the important cpu instructions? Maybe keyboards and text editors are making us soft, and we should create programs manually with punch cards.

------------------
+---------+
|steveth45|
+---------+

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
at the ACM programming competition (basically a global deal where university teams of 3 (my college was an underdog) have 5-6 hours to solve a handful of complex computing problems. the team has one computer so everyone has to write their code on paper first and then type it up to test it.
samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
I don't code on paper, but I do build UML diagrams on index cards. Kinda like, but not as fanatical as a Hipster

I take notes and ui sketches, etc. as well. I like index cards with a binder clip because I am a random thinker and I can shuffle them around into a more coherent sense later.

------------------
Sam Washburn

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
I rarely use paper but when i do it can be real useful.

anyways i just thought that i should show those of you learning c++ a cool algorithm,very simple and mostly useless,the following code gets a character from cin and displays the ascii and binary value of the code.


#include<iostream.h>
int main(){
char c;
int i;
cout<<"enter any character:\n";
cin>>c;
for(int j=0;j<32;j++){
cout<<c%2;
c=c/2;

}

return 0;
}


i just thought you should know a bit about the % operator ,you can change c into an integer. i just wrote this code at school so i haven't tested it yet ,i am sure there are many ways to make it look better,like padding all the zeros at the end ,etc....

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

[This message has been edited by spade89 (edited January 30, 2007).]

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok, i need to know what to use to split the string for my calculator. i guess i should check out msdn, eh?

------------------
~~~boogie woogie woogie~~~

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
you may be better off with a quick google instead. MSDN is fairly useless sometimes
bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
true enough..

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
Uh.. spade, your 'i' var is uninitialized and you aren't using the 'c' you read in.

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok let me talk this out... it helps me a lot.

ok to do the blah-plus-blah-times-blah-minus-blah-divided-blah-etc. i have to get the string from the user. lets call it exp (short for expression)

string exp;
cout<<"Enter the expression ";
cin>>exp;
cin.ignore();

alright, we wont know how many operators we will receive so we have to figure that out first. I thinking, maybe use an array. Split the string up and place them in the array, then count how many items we have in the array, do a loop and solve the math problem.

...and that is where i'd be stuck.....

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
I'd say build a calculator that handles only one operator at a time... like the one on your desk. Start small.

The multi-operator version will require recursion or a stack.. higher level stuff. (That is if you want to keep the mathematical order of operations intact.)

------------------
Sam Washburn

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
reverse polish notation would be fun for that type of calculator design
bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
i've finished the basic calculator a few days ago..


#include <iostream>
#include <string>
using namespace std;

int num1()
{
int n1;
cout<<"Enter First Number ";
cin>>n1;
return n1;
}
int num2()
{
int n2;
cout<<"Enter Second Number ";
cin>>n2;
return n2;
}

void showAnswer(int ans)
{
cout<<"The Answer Is: " << ans << "\n\n";
}

void showMenu()
{
int opt;
cout<<"------------\n";
cout<<"Menu:\n";
cout<<"1. Addition\n";
cout<<"2. Subtraction\n";
cout<<"3. Multipulcation\n";
cout<<"4. Division\n";
cout<<"5. Enter Expression\n";
cout<<"0. Quit\n";
cout<<"Choose an item from the menu and press enter ";
cin>>opt;
cin.ignore();
int number1;
int number2;

if (opt != 5 && opt != 0)
{
number1 = num1();
number2 = num2();
if (opt == 1)
{
showAnswer(number1 + number2);
}
if (opt == 2)
{
showAnswer(number1 - number2);
}
if (opt == 3)
{
showAnswer(number1 * number2);
}
if (opt == 4)
{
showAnswer(number1 / number2);
}
showMenu();
}
else if (opt == 0)
{

}
else if (opt == 5)
{
string exp;
cout<<"Enter an expression and hit enter ";
cin>>exp;
cin.ignore;

}
else
{
cout<<"Please choose an item from the list.\n";
showMenu();
}


}


int main()
{
cout<<"bwoogie's calculator\n";
showMenu();
}

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
Good Job!

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
thanks sam. it was easy since i've had plenty of programming experience in other languages. but c++ is quiet different than any other language i've used really.

i wish i would have started with c++. then by now i'd know how to program with it better (i would think) and i could work on my game haha. wow i want to make my game. oh well, i will keep practicing. what should i write now?

------------------
~~~boogie woogie woogie~~~

HeardTheWord

Member

Posts: 224
From: Des Moines, IA
Registered: 08-16-2004
bwoogie,

Good work! To get the number of characters in a string use the size() function. In your case it would be exp.size() and to get the characters do something like the following.

for(int i =0; i < exp.size(); i++) {
char blob = exp[i];
// do something with the character here
}

Do a google search on parsing and you will probably come up with some examples on how to split apart the string. It's a lot trickier than you might think.

[This message has been edited by HeardTheWord (edited January 27, 2007).]

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
Last night, i was at my church and i was messing on the mac (im involved in the audio/video team) and i brought my calculator code and compiled it and was happy to see it run on os x.

Anyways, learning c++ is fun, but a pain at the same time. weird. but yeah. please give me suggestions on what to write next.

------------------
~~~boogie woogie woogie~~~

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
i haven't used c++ keyboard handling much but i used the kbhit() function to determine what the user wants to do... like the user enters 1 then we wait for kbhit() then we get a char (i used getch(),but you could probably use cin.get()) to see if the next thing is +-*/ .......

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
How about a "guess my number" game?

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
quote:
Originally posted by samw3:
How about a "guess my number" game?


ok sounds like a good idea. i will start on that today.

------------------
~~~boogie woogie woogie~~~

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
what's a "guess my number" game?????

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
quote:
Originally posted by spade89:
what's a "guess my number" game?????


The computer pick a number from 1 to 100 and prompts "Guess my number?". And the user types number to guess it. With each guess the computer responds "Higher", "Lower", or "You Guess It!" depending on the guess.

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
Ok, i'm finished. But i noticed a bug, the answers are always the same. 42, 68, 35... I know random numbers aren't really random.. but this is just pitiful. what did i do wrong?

p.s. i used a pointer!


#include <iostream>
using namespace std;

void check(int answer);
void guess();
int *pointer;

int main()
{
int randint;
randint = (rand()%100) + 1;
pointer = &randint;
cout<<"I'm thinking of a number between 1 and 100\n";
guess();
}
void guess()
{
cout<<"What is your guess? ";
int myguess;
cin>>myguess;
cin.ignore();
check(myguess);
}
void check(int answer)
{

if (answer > *pointer)
{
cout<<"Your guess was too high. Try again\n";
guess();
}
else if (answer < *pointer)
{
cout<<"Your guess was too low. Try again\n";
guess();
}
else if (answer = *pointer)
{
cout<<"YOU WIN!";
main();
}
}

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
First of all, you are just cranking it out! Great Job! The reason why the numbers are the same is that the random number generator needs to be seeded since it is only a pseudo-random number generator.

Most people seed the generator by the internal timers like so:

srand((unsigned int)time(0));

EDIT: You have another nasty bug: a recursion stack overflow possibility.
Since you keep calling the main function when they win, but technically you are still in the main function's scope, if they keep playing and playing at some point you will run out of stack. It might be like 100000 games to hit it tho.. depends on your platform, but its still good to know its there.

But its a really interesting way to build the game without any loops.

------------------
Sam Washburn

[This message has been edited by samw3 (edited January 30, 2007).]

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
yeah i was really wondering about calling the main function from within another... but i was hoping that the compiler would yell at me saying it was a bad idea... and since it didnt, i left it. but yeah, i know its a bad idea.

------------------
~~~boogie woogie woogie~~~

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
You seem like a pretty creative coder, boogie. I'd really like to see you do a sort, if you are up to the challenge.

1. Take a 20 element array
2. Fill it with 20 random numbers from 1 to 100
3. Print the numbers on the screen
4. Sort them from lowest to highest.
5. Print them again sorted.

then, of course, show your code
------------------
Sam Washburn

[This message has been edited by samw3 (edited January 30, 2007).]

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
thanks. that really encourages me. calling me creative. i do appreciate that.

so, here she is! it look some research. i got it figured out.

#include <iostream>
#include <cstdlib> //used for srand
#include <ctime> //getting the time to make random numbers
#include <algorithm> //sorting

using namespace std;

int main()
{

//create the array of random numbers
cout<<"Unordered Random Numbers\n";
int arr[20];

//Great discovery! srand MUST NOT be in the loop!
srand((unsigned)time(NULL));
for (int x = 0; x<20; x++)
{
arr[x] = (rand()%100)+1;
//print out the number just created
cout<< arr[x] <<" ";
}
//Sort the numbers
sort(arr,arr+20);
//and print them out
cout<<"\n----\nSorted Numbers\n";
for (int z = 0; z<20; z++)
{
cout<< arr[z] <<" ";
}

cin.get();
cin.ignore();
}

------------------
~~~boogie woogie woogie~~~

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
i have to say you are more creative than most begining c++ coders ,it must be because of your previous coding experience. and if you want to learn more about sorts try building your own like bubble sort or quick sort , instead of using the standard libraries.

i think www.cprogramming.com has some good tutorials , and if you are interested try googling for the tower of hanoi problem, or the fibonacci numbers(if you are interested in recursion). i never used it much but comb sort is supposedly real good with large amount of items.

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
I second his www.cprogramming.com tutorials. I'm currently learning through them. Confused by Commandline arguments, and Linked Lists though. I'm also confused on how to use Classes.

Another site which contains great tutorials is www.aihorizon.com it mostly covers AI, but has some useful information about linked lists, ext.
------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

[This message has been edited by Mene-Mene (edited January 31, 2007).]

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
what do you want to know about linked lists?
Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
I just don't understand them, or how to declare them. I don't see a ton of good in them, and the tutorials didn't really complete my understanding of them.

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
ok.... well lets try this:
a list is a container. other containers are vectors, stacks, queues, etc.

think of a list as a conga line; each person in the line is holding onto the next person's shoulders. that's essentially a single-linked list.

one link in the list (a link is one item in the list) could look like this:

// pseudo-code
class link{
int itemToStore;
link* nextLink;
}

each link in the list holds a pointer/reference to the next link. so if you're iterating through a list:
// definition
link currentLink;
// move to the next link
currentLink = currentLink->nextLink;


thats essentially what a linked list is. the plus's but a linked list is that it's easy/fast to add new links. you just find the last link and make its reference point to a new link.

the downside is that it takes a long time to iterate through. well, longer then say an array or vector.

questions?

Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
Ok... First question. Why?

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
ok, well arrays have a static length. if you have 10 elements and 11 objects to store, then you have to create a new array with 11 elements and copy all the data from the first array; thats a lot of work. so with a linked list, you dont' have to know how many objects are going to be stored because you can just keep adding more.
Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
Ah, so say you have a bunch of bullets, you never know how much the player is going to need, so a linked list would solve that problem.

Forgot Question 2. Oh Well, I'll try and see how to work it. I understand it, just not how to put it together. Like I understand that an engine uses cylinder's ext. for power (Not going through and explanation right now), but I don't know how to put one together.

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
yes and no. you get the idea and it could work but it would probably work slowly if you were reading from the list a lot. a vector would probably be a bit more beneficial. it has dynamic length (handled implicitly) but its faster for iterating through. in C++ (STL) it's gauranteed to have sequence memory addresses.
bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
quote:
Originally posted by spade89:
i have to say you are more creative than most begining c++ coders ,it must be because of your previous coding experience. and if you want to learn more about sorts try building your own like bubble sort or quick sort , instead of using the standard libraries.

i think www.cprogramming.com has some good tutorials , and if you are interested try googling for the tower of hanoi problem, or the fibonacci numbers(if you are interested in recursion). i never used it much but comb sort is supposedly real good with large amount of items.


erhm, not really interested in learning much more about sort. i know it can come in handy.. but i dont see that it is extremely important right now.. is it?

------------------
~~~boogie woogie woogie~~~

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
it's more the mindset thats a good idea to develop. if you can solve the bubble or quick sort algorithms by yourself then you're more likely to succede with other algorithms.
spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
i mostly use linked lists i made myself(reinventing the wheel) not the ones in the stl, the main purpose of linked lists is to give you a place to store your data and the space is limited only by the virtual memory of your system, supposedly dbms's use linked lists and many other database related systems do that too, let's say you have a program that keeps track of students inside a school, their grades, behavior,extracurricular activities,etc... then you can't use an array because you don't know how many students may end up in your school, so you have no choice but to use a linked list, there is also something called a tree, in a tree no two items are the same and many algorithms(like huffman coding which i am trying to learn now) use trees.

as for command line arguments let me give you an example:


int main(int argc,char **argv){
if(argc>1){
cout<<argv[1];
}
else{
cout<<"please enter an argument through a command line \n";
}
}

you can run a program like this using the run command in windows or using the command prompt.
when you run the program you type the programs name and an additional argument like this:

myprogram.exe mene-mene

when you type the above thing it brings up a program that displays mene-mene .

argc is the number of arguments passed so if the program was to display]
cout<<argv[1]<<' ';
cout<<argv[2]<<' ';
cout<<argv[3]<<endl;
and you runned the program like:
myprogram.exe mene-mene likes c++


this program will display:
mene-mene likes c++

let me give you an example of how windows uses this to copy a file if you just open the command prompt and let's say you have a file called file.jpg

and you type copy file.jpg c:\

this will copy file.jpg to c:\
so copy would be the program and file.jpg and c:\ would be the two argumetns, so in the program copy it is using the array argv as a normal array(this can be an alternative to using cin,cout for simple tasks ).

there is something also called the environment pointer.
which we use like:
void main(int argc,char **argv,char ** env){}

but that is another story ,try googling for it or something.

or better yet let me give you an example program and try to figure it out by yourself


#include<conio.h>
int main(int argc,char **argv,char ** env){

for(int i=0;i<64;i++){
cout<<"environment variable "<<i<<"= "<<env[i]<<endl;

}
getch();
return 0;
}

try pressing control+break when system properties comes up click on the advanced tab and press the environment variables button and see if the stuff in there resembles what this program displayed.
¢¼

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
bwoogie:

yeah it is important if you are thinking of being a professional c++ programer you would be able to build your own algorithms based on the sort algorithms and you might really need them in some of your programs.

even if you think you won't you don't want to have to learn this later when you have known everyting else, you are better off learning it now.

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
you're right. i'll keep learning about it now then. just seems kinda boring right now. but i guess it will be less boring now than later.

------------------
~~~boogie woogie woogie~~~

SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
I agree. Learning sort routines is very helpful in gaining a foundation in understanding algorithms. In fact, if I remember correctly, sorting and trees were a first year topic in college.

Learning and understanding different sorting algorithms will also help you understand why certain search algorithms are faster than others, as well as when and why to use certain containers. It goes beyond sorting.

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
actually i did sorting algorithms in my process logic class (no programming involved). anyways, just wait until you're doing red/black trees
samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
@boogie What are you interested in? Why are you learning c++? Games?

------------------
Sam Washburn

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
games mostly but regular applications too. just ready to move on to something more powerful. and something more commonly used and maybe get me a job.

------------------
~~~boogie woogie woogie~~~

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
you chose the right language ,c++ is the industrys standard.

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by SSquared:
In fact, if I remember correctly, sorting and trees were a first year topic in college.

Then you find out that all the sorting routines are already built into most code libraries like STL and .NET, and that you'll probably never have to implement a tree.

Just kidding. I had to write a sort algorithm just the other day--the library ones don't always fit the task at hand. You'll want to know trees, too, in case it comes up in an interview or programming test for a job. I wouldn't stress out too much about having to implement them for production code. Hash tables are much faster and simpler than trees for most purposes. If you implement a hash table properly, the search time is O(1). Doing a search of an balanced tree is roughly O(log n). In layman's terms, trees take longer to search as they grow, hash tables do not.

------------------
+---------+
|steveth45|
+---------+

SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
And it wasn't too long ago that on this VERY site we were discussing Hashtables in C++ vs. C#. Steveth discovered the unlikely outcome of C# being quite a bit faster than C++. We discussed, researched, and had an interesting conversation.

In fact, it was just yesterday I was telling someone at work about that very thread.

So...it does come up in my own conversations every so often as well.

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
hmm. ok, i need help. i dont even know where to start on this sorting thing.

------------------
~~~boogie woogie woogie~~~

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
google some stuff on the bubble sort. its the most basic in my opinion.

and thats kinda surprising about C# being faster then C++. STL has been around longer then C# and C# is an interpreted language so its a little odd. anyone have a link to that thread? or perhaps the abliity to sum it up?

SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
Sorry, I don't know how to do a link to the thread. It was actually from way back in May 2006. Boy! I thought the thread was like 2 or 3 months ago. The title is: "C sharp versus C plus plus"
steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by jestermax:
and thats kinda surprising about C# being faster then C++. STL has been around longer then C# and C# is an interpreted language so its a little odd. anyone have a link to that thread? or perhaps the abliity to sum it up?

Actually, C# gets compiled "just-in-time", which means that when you load an application, there is a slight delay as the byte code is compiled into machine code, then it runs at full speed. I don't know about C# being faster than C++ in general, but it does handle strings more efficiently (faster) than STL strings with C++. Don't get me wrong, I love the STL, and I think its capabilities go well beyond .NET as far as fast, generic data handling. .NET is really oriented toward writing GUI applications, and STL is better suited for games. I don't think C# will ever compare with C++ for dealing with large chunks of data and rapid I/O regarding sound and video hardware. If you see a fast game written in C#, it was probably written in C# on the surface, but is really just making calls into a C++ based game engine.

------------------
+---------+
|steveth45|
+---------+

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
so.... remind me why C# needs to be compiled just in time? with Java, it runs on any operating system with a JRE but what's the reasoning for .NET?...
steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by jestermax:
so.... remind me why C# needs to be compiled just in time? with Java, it runs on any operating system with a JRE but what's the reasoning for .NET?...


Well, the JRE is very similar to the CLR. These days, Java is also compiled JIT. Microsoft created C# and most of the .NET framework as an open standard, which allows other people to create implementations of .NET and C# compilers. That's exactly what the Mono project is. I've compiled C# programs in Windows and ran them in Linux with Mono. Although Windows hasn't supported or aided in the implementation of .NET on non-Windows platforms, JIT compilation on 32 bit and 64 bit versions of Windows, will produce different code that is more optimized for the specific processor that is being used.

------------------
+---------+
|steveth45|
+---------+

SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
Actually, there is a tool (forget its name) which can precompile an executable for use on a particular machine. It is part of the Visual Studio Installer package. Since the installer is run individually for each machine, this little app will run specifically for the current machine.

In the end, you have a pre-compiled .NET app. With one caveat. I do believe it will only run on the specific machine. You can't copy and run it on someone else's computer.

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok, bubble sorting.
I understand how it works now. Extremely simple. The only confusing part is the loops. But its really not that hard once you get your brain to think straight. i found some code online and rewrote it allowing myself to peak at it the first time. then the second time erased it and rewrote it by myself.


void bubblesort(int x[], int a)
{

for (int pass = 1; pass < a; pass++)
{
for (int i = 0; i < a-pass; i++)
{
if (x[i] > x[i+1])
{
int temp = x[i];
x[i]=x[i+1];
x[i+1]=temp;
}
}
}
}

------------------
~~~boogie woogie woogie~~~

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
ok, while you guys are grading the sorting deal, i decided to read up on Classes. Simple enough to understand. I went ahead and wrote my "coolness" class.


#include <iostream>
using namespace std;

class coolness
{
public:
coolness();
~coolness();
void setcool(int i);
int getcool();
protected:
int coolrating;
};

coolness::coolness()
{
coolrating=0;
}
coolness::~coolness()
{
}

void coolness::setcool(int i)
{
coolrating=i;
}
int coolness::getcool()
{
return coolrating;
}

int main()
{
coolness cool;
cool.setcool(1000);
cout<< "your coolness rating is " << cool.getcool();
cin.get();
cin.ignore();
}

--Edit:

whoa, structures are awesome! those would come in extremely handy for keeping track of stats in a game! i love C++!!!!

[This message has been edited by bwoogie (edited February 03, 2007).]

[This message has been edited by bwoogie (edited February 03, 2007).]

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
the class looks good. one thing though, when you're initializing in your constructor, use this format:

coolness::coolness() : coolrating(0)
{
}

but bottom line, they do the same thing so good job

oh yeah, classes aren't structures. they're similar in many ways but different enough to be considered different

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by jestermax:
oh yeah, classes aren't structures. they're similar in many ways but different enough to be considered different

In C++, the only difference is that the members of a struct are public by default and the members of a class are private by default. Since the public and protected members of the above "coolness" class are explicitly defined, you could replace the class declaration with struct, and it would work exactly the same.

Using struct in C++ is usually just a signal to those reading the code that you are making some plain old data structure and not necessarily a complex object. This is because of the history of struct in C, but there is no practical reason in C++ that you can't use them interchangeably for both purposes.

------------------
+---------+
|steveth45|
+---------+

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
i know classes and structures are differant! i just made an edit so i wouldnt tripple post.

------------------
~~~boogie woogie woogie~~~

Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
I'm starting to get lost in classes/OOP programming. I'm used to a BB/Basic style of programming, and I've currently been trying to force structured programming on C++.

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
if you think structs are cool wait until you get to inheritance and polymorphism--game coders love them. oh and btw there is this opengl tutorial that exclusively uses structs(as far as i saw) @ http://www.spacesimulator.net .

if you think you know pointers pretty well by now, try using pointer to objects.
like :


coolness *cool;
cool->setcool(1000);
cout<< "your coolness rating is " << cool->getcool();

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

Mene-Mene

Member

Posts: 1398
From: Fort Wayne, IN, USA
Registered: 10-23-2006
I know structures, just not classes.

------------------
MM out-
Thought travels much faster than sound, it is better to think something twice, and say it once, than to think something once, and have to say it twice.
"Frogs and Fauns! The tournament!" - Professor Winneynoodle/HanClinto

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
classes are to structures like c++ is like to c, the main thing you should know beside the syntax is a data member(such as an int an object) declared in a struct like :

struct x{
int i;
char x[32];
}

these variables inside x are all public i.e. anyone can acces them using an object of x like
x obj;
obj.i=9;

but in a class if you do the same thing:


class x{
int i;
char s[32];
}

in this case you can't say:
x obj;
obj.i=9;
that will make an error because s and i are both private,so you have to un-private them by using public keyword like:


class x{
public:
int i;
char s[32];
}

in classes the compiler treats all members not declared public as private
but in structs everything is by default public. the use of structs is mainly to group data,but in classes it is to group data and to encapsulate it(by saying public/private).

btw, have you learned about a union variable?
and you should also practice with the stl and try finding(and using) fuctions in the headers that come with your compiler.

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
yeah, unions are cool, everything occupies the same memory space. Here is a common usage:

union my_string
{
char * text;
unsigned int unique_id;
}

On a 32 bit system, a pointer is 32 bits, and an unsigned int is also 32 bits, so an instance of this union will only be 32 bits.

my_string str1;
my_string str2;
str1.text = new char[10];
str2.text = new char[10];

Now, the values of str1.unique_id and str2.unique_id are basically the memory locations of the char array that they point to, since these strings were initialized separately, the unique_id is, of course, always going to be different. It can be super dangerous of course, don't do this:

str1.unique_id = 1234; // do you know what's at that memory location?
cout << str1.text; //who knows what this will print? maybe it'll crash.
str1.text[3] = 'M'; // You could be trashing the stack, or worse. Hopefully the program will crash and nothing worse.

You can safely code in C++ without using unions.

------------------
+---------+
|steveth45|
+---------+

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
steveth:
quote:
This is called productivity. Maybe you think variable declarations are numbing our programmer minds and we should deal strictly with memory locations in hex and write all our code in ASM. ASM, however, is a layer of abstraction between you and the cpu, why not code directly in hex by memorizing the hex values for all the important cpu instructions? Maybe keyboards and text editors are making us soft, and we should create programs manually with punch cards.

If that was directed at me your so far off it's just stupid. I don't know if you were trying to be funny either, but it wasn't... BTW, I wasn't bagging Intellisence... I use it all the time (and definitely at work) and I know it's awesome.

Just for a beginner (and when someone is just learning), it isn't much of a concern to use it or not, as your only working on say 1-10 code/header files and at most about 1-2k lines of code. You *should* be able to juggle the classes/structures/functions/etc. in your head or on paper for the duration of the project. However, on larger projects (professional or hobby) you definitely need it. Also it's just some advice which I've found helped me... and it seems others have used it too...

------------------
www.auran.com

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by dartsman:
steveth:
If that was directed at me your so far off it's just stupid. I don't know if you were trying to be funny either, but it wasn't...

I was just joking around, as were you. You called Visual Assist "evil," right? That was a joke, and so was what I wrote. What if the people who wrote Visual Assist read your message and got offended and thought what you said was "stupid" and not funny? If you write a humorous overstatement, and somebody responds in kind, you can't take offense.

As for my comment, I thought it was funny when i wrote it, but you're probably right, its stupid. What's even stupider and certainly not funny is a translation of what I wrote into Ebonics:

quote:
Originally posted by steveth, translated into Ebonics:

Intellisense iz great, so what if ya don' remember if da variable iz named numThis or numThat, ya hit da period an' type "nu" an' hit enter. This iz called productivity. Maybe ya th'o't variable declarations iz numbing our programmer minds an' we's should deal strictly wiff memory locations in hex an' write all our code in ASM. ASM, however, iz uh layer o' abstraction between ya an' da cpu, why not code directly in hex by memorizing da hex values fo' all da important cpu instructions? Maybe keyboards an' text editors iz making us soft, an' we's should create programs manually wiff punch cards.

Now everybody is offended .

------------------
+---------+
|steveth45|
+---------+

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
right....

------------------
www.auran.com

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
if the people who wrote visual assist are on CCN then thats probably one up for us. and if they get upset from one guy saying he doesn't like their software then i THINK they have bigger problems on hand.

I have to say i'm siding with dartsman on this; beginner programmers should stick to a notepad style editor for writing code. its the next best thing to a pad of paper and makes it so you're more than just a script kiddie. No, i am not bashing visual assist/intellisense either.

When i first started coding Java, my instructors got me to do it in notepad. It as annoying as anything but when i moved on to an IDE i actually knew what was going on and what the tools were doing for me.

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by jestermax:
When i first started coding Java, my instructors got me to do it in notepad. It as annoying as anything but when i moved on to an IDE i actually knew what was going on and what the tools were doing for me.

I took a class on Java in 1997, and we used Java 1.0 with CodeWarrior on Macs... it was not a pretty sight. It was the first term that they used Java at the university and most of the professor's example programs didn't even compile. This was before Java had the JIT compiler, so it was just, plain slow. My project for that class was a web-applet game... my first game, technically.

------------------
+---------+
|steveth45|
+---------+

samw3

Member

Posts: 542
From: Toccoa, GA, USA
Registered: 08-15-2006
I may be preaching at the choir, but..

I can personally vouch that, no matter what the language, any IDE assistance is a performance booster.

I think telling programmers they have to write code in notepad is akin to telling technical writers they have to use notepad as well.. no spell check, auto page numbering, table formatting, etc.

Now, I can understand that budding coders who use the GUIs that add classes and methods and even refactor push downs and pull ups; how they may never know how to read the code because they never see it.

BUT, tools like dynamic syntax checking, bracket/brace completion/tracking and object/method drill-downs are essential to code fast (at least they are for me). Even M$'s dynamic help system, which was snubbed to begin with, is faster than looking it up in a manual or googling it. Sure some people can pull every function out of their head. These are probably the ones that only know one language, and will be out the door when their language of choice goes the inevitable way-of-the-dodo.

I think the most important thing for new coders to learn is algorithm design, and not just for one language. Can you do a red-black tree in all the langs you know? Do you know when to use one?

That's the stuff even the most brilliant IDE will not be able to help you with. I say let the IDE do all the boring drudge work of syntax proofreading and moving stuff around. Syntax is just a intermediate language between your brain and the compiler.

With my experience, if I was going to hire a coder I would look for:
1) Their grasp of algorithms and design patterns
2) How well they can *read* code (regardless of language)
3) How well they can design a solution to a problem. Even if its only in UML.

I would avoid a coder who:
1) Claims to be a specialist in only one or two languages
2) Can produce but cannot read code
3) Rewrites code instead of refactoring it

------------------
Sam Washburn

[This message has been edited by samw3 (edited February 06, 2007).]

steveth45

Member

Posts: 536
From: Eugene, OR, USA
Registered: 08-10-2005
quote:
Originally posted by samw3:
I think telling programmers they have to write code in notepad is akin to telling technical writers they have to use notepad as well.. no spell check, auto page numbering, table formatting, etc.

... tools like dynamic syntax checking, bracket/brace completion/tracking and object/method drill-downs are essential to code fast (at least they are for me).


I agree 100%. Memorizing the details of the syntax is not programming, its just learning a syntax. If the IDE automatically indents for me, or reminds me if I need () or [] or <>, that's fine. I know the algorithm, so who cares about the syntax of the ugliest and most powerful language of all time (C++).

------------------
+---------+
|steveth45|
+---------+

SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
All good points! I totally agree.

> That's the stuff even the most brilliant IDE will not be able to help you with.

Actually, Visual Studio does have code snippets, so if someone were to write the snippet, the IDE will have immediate access to adding it to your code. Please note, there IS a hint of sarcasm in what I am saying.

Memorizing syntax is hard. Especially when you are dealing with several different languages. When I am interviewing someone, I look beyond the syntax and am much more concerned with their understanding of the problem and their thought process. When I am nervous, like in an interview, I know the feeling of forgetting little syntax things.

Any tool to make a developer's job more productive is a plus...balanced with the developer still understanding the task/job/code. In other words, like Sam stated, I am not a big fan of Wizards spitting out a bunch of code the developer never needs to understand. I've seen this and the result is the person does not understand event models which is key to really understanding user interfaces.

Now, with all that said, I do believe when I started programming, I just penciled out the code. I stepped through everything by hand until I felt it was ready. Then I would type it all in. This was a terrific way to learn what I was trying to accomplish, but there also were no great editing tools at the time (I used 'vi').

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
just to state my points which I made to those who might have taken what I said the wrong way (reading what you want to hear)...

I never was saying you should only code in notepad, or just use notepads, or that IDE assistance is evil. Just that the dependencies to which you become reliant on with the particular IDE or 3rd party tool.

It was just some advice...

------------------
www.auran.com

spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
for serious professional coding 3rd party tools and visual editors are very important but i don't see their use for someone just trying to learn how to code(other than roat their brains).

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
ugh, this has turned into an argument when really we all agree on the basics. everyone here agrees that a good IDE is gold in this business. intellisense is a blast and speeds up development time (time is money).
Here's the part that it seems that some agree with and some don't:
beginners should use notepad editors for coding.

This is not to say that they should always stick to that; this is saying that until they get a decent grasp as how to write proper code and what actually happens with the compilation process. that's all. it's not a hazing thing or some form of initiation. this was advice given in hopes that whoever takes it will be a better programmer later on.

bwoogie

Member

Posts: 380
From: kansas usa
Registered: 03-12-2005
why not just let the person decide for themselves which they want to use?
anyways, if you guys want to continue that discussion, please move it to a new thread. Thanks.

------------------
~~~boogie woogie woogie~~~

jestermax

Member

Posts: 1064
From: Ontario, Canada
Registered: 06-21-2006
we're not saying that anyone should do anything. we were just fighting over the best advice to give to someone just starting off, at least thats how it started. Anyways, sorry for hijacking your thread
Any more C/C++ related questions?
spade89

Member

Posts: 561
From: houston,tx
Registered: 11-28-2006
i was looking at mit's open course ware program and i found this c++ tutorial, not detailed but if you are an experienced coder then you may like it, it's in pdf:
http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-837Fall2003/D8D8C404-7351-4660-94B5-F80B0C52D6EA/0/1_2_cpp_tutor.pdf

------------------
Matthew(22:36-40)"Teacher, which is the greatest commandment in the Law?" Jesus replied: " 'Love the Lord your God with all your heart and with all your soul and with all your mind. This is the first and greatest commandment. And the second is like it: 'Love your neighbor as yourself.All the Law and the Prophets hang on these two commandments."
Whose Son Is the Christ

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
I'm learning C++ in my spare time right now, and I'm wondering about manually destroying objects. I found that "objectreference.classname::~classname()" can do this, but I get some trouble because the objects still end up on the receiving end of the implicit destructor call at the end of main().

On the other hand, it may not be all that useful to actually destroy an object instead of simply setting an "isalive switch." If I simply use a switch mechanism, then I can retain state data until program exit. However, all of that data will remain in memory, which could cause problems if the data is large enough. Basically, I'm messing around with general RPG ideas while getting a handle on C++, and I can't figure out which technique would work better with holding data for the various characters.

Any recommendations would be greatly appreciated. I'm trying to figure out best practices for game development.

------------------
If games please me, and if it's possible to please God with games, why on earth wouldn't I make games?

SSquared

Member

Posts: 654
From: Pacific Northwest
Registered: 03-22-2005
Explicit or implicit memory deletion is based on how you allocate the memory.

If you write: MyClass myClass;
then MyClass will be deleted when leaving scope. The destructor will be called automatically. You do not want to explicitly call delete in this case.

If you write: MyClass* myClass = new MyClass();
then you must explicity call delete from within the same scope you allocated the data. In this scenario, you are creating the memory and are responsible for cleaning it up. This is where memory leaks come into play. If you don't delete it, you get memory leaks. So memory allocation and deletion come in pairs. Sometimes people forget the delete.

There is something called a Smart Pointer some programmers use which automatically knows when to delete your allocated memory. I haven't used them in years, so I can't remember the exact syntax. A Google search should turn up good information.

Languages like C# and Java have automatic memory management and will free the memory with something called garbage collection.

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Thanks for the info, ssquared. I'm familiar with memory leaks; that's what I was wanting to avoid.

My next question is, though it seems it's come up already in this thread, if I want to have spaces in my strings, should I be using the string type/class? I've always done things with character arrays, but I wonder if I'm better off using strings. Are there any real disadvantages to using strings over character arrays?

Thanks!

------------------
If games please me, and if it's possible to please God with games, why on earth wouldn't I make games?

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
I downloaded the SDL libraries, and am using it with Code::Blocks in Mac OS X. It seems to be a pretty sweet combination (C++ is my language of choice right now). I've given thought to working with DirectX and VisualC++, but I like the idea of making things that are more easily ported. Anyway, SDL seems to be quite capable of 2D stuff, which is exactly what I'm looking for.

------------------
If games please me, and if it's possible to please God with games, why on earth wouldn't I make games?

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Triple post! Too bad that's usually frowned upon.

I'm having a lot of trouble with my switch statements in my map generator right now. So long as I only have two cases (or a case and a default), everything works fine. Unfortunately, that doesn't help me much. I've tried using if/else if to make sure that there wasn't just some syntactical error in my switch, but the problem persisted. The problem, to clarify, is that my app crashes on load when I have two or more cases in this one switch. I'm using similar switch/cases elsewhere, and I've had no problems with them.

Here's my code (HTML is disabled on my account, I think, so I can't do pre-formated text; in other words, indentation won't be right):

EDIT: I found out about "code" as a BBCode tag. I've fixed this post.


int createArena(int startx, int starty, int onwall)
{
int countx = 0, county = 0;
switch(onwall)
{
case 0:
// The North wall of this room attaches to the above room.
// Check the area for space for a box room.
startx = startx - generateNumber(2,3);
for( county = starty ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 8) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
return 0;
break;

case 1:
// The East wall of this room attaches to the room to the right.
// Check the area for space for a box room.
startx = startx - 8; starty = starty - generateNumber(2,3);
for( county = (starty - 1) ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 7) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
return 0;
break;

case 2:
// The North wall of this room attaches to the above room.
// Check the area for space for a box room.
for( county = (starty - 1) ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 8) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
return 0;
break;


case 3:
// The North wall of this room attaches to the above room.
// Check the area for space for a box room.
for( county = (starty - 1) ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 8) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
return 0;
break;

default:
// The room is the central room, and has no immediately joining room.
// Thus, there is no need to check for space.
buildArena(startx, starty);
return 0;
break;
}
}

By the way, buildArena takes two integers (which are correctly being passed), and is a void function. I'll probably change that to returning an int for added error detection, but I didn't find it immediately necessary since I'm already checking for the space needed for the buildArena function to succeed (there should be no possibility of failure).

Any help whatsoever would be much appreciated! Thanks!

------------------
Portal with information on my programming projects and links to my other work

[This message has been edited by Xian_Lee (edited March 31, 2007).]

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
wrap your case blocks with {}

eg.

switch(val)
{
case 1:
{
// code...
}
break;
case 2:
{
// code...
}
break;
}

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

[This message has been edited by dartsman (edited March 30, 2007).]

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
I'm pretty sure that I've tried that, but I'll do it again. Thanks for the tip!

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
whats to stop 'layout[county][countx]' going out of the bounds of layout?

You should check that county/countx are not < 0 or > then your max size...

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
That's probably what I've been overlooking! So simple, and yet, so devastating to a program flow. That's why I posted here, so that someone could see where my code was failing and help me out.
Thanks!

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
no problem, you were most likely just accessing some random memory outside the bounds of the array.

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Quite probably. Especially since adding the blocks didn't do anything. Hopefully this will work! Thanks again! If Code::Blocks would quit having issues (blasted makeshift Mac version), I'll be able to get this running.

------------------
Portal with information on my programming projects and links to my other work

AndyGeers

Member

Posts: 45
From: London, UK
Registered: 06-20-2005
Adding { and } is nice formatting but it will make zero difference to the behaviour. Another thing that won't make any difference, but will save you a bit of typing, is don't bother putting a "break;" straight after the "return;" - the break isn't required syntax, and will never get executed because of the return running first.

Did the bounds checking fix your problem? A common error with for loops and an array is going one too far - e.g. if you have myArray[5] then you loop for (i = 0; i <= 5; i ++) but myArray only actually goes up to 4 cos it's 0 offset.

------------------
http://www.geero.net/

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
Good formatting is good to teach hehe

If the bounds checking doesn't help, the 'buildArena(...)' most likely has a problem... please try and post code in the '[code]' blocks with the indentation :P

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
I didn't realize there was a "code" tag in BBCode. My bad. I thought it was just HTML, and I can't get HTML to work for me.

In any case, I haven't gotten my code to work yet. I'm going to try to do it in the console instead of trying to build it and get SDL to display it.

------------------
Portal with information on my programming projects and links to my other work

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Sorry about the double post.

I copied the code over to another machine and built a simple driver for the map class I was working on. It was a simple console-based test for the class, and everything compiled and ran exactly as it should have.

I made no significant changes to the source code of the class, so I'm thinking that there's something else going wrong. Of course, it's going to be hard to figure out if something's going wrong in Code::Blocks, the way Code::Blocks tries to execute my code, or there's something odd going on with my SDL tie-ins. However, since that switch/case seems to be what the success or failure of the system depends on, I'm a bit at a loss in regards to finding the issue.

Regarding the possibility of getting out of the bounds of the array, I tested against it, but had no such luck in fixing the problem.

If anyone has some other insight to share, I would love to hear it!

The results of my mapping function actually look kind of good in the console system. The maps can be kind of nonsensical, but they function.

I'm running out of ideas as to why this isn't working.

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
what is Code::Blocks? i'm guessing it's something with SDL, but i've never used SDL so I have no idea... though unless if you find your crash with a simple google search, it's most likely just either your code, or the way your trying to do something...

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Sorry for not clarifying, Code::Blocks is an open-source C++ IDE. I'm only using SDL because I don't have DirectX on the Mac, and it looked easy enough to set use. Now, I'm not certain at all where the problem is with my code. I think I'll try compiling it outside of Code::Blocks and see if that helps. I'll go from there. Thanks for the tips, I'll see if I can find anything based on them.

This is going to drive me crazy.

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
you could try posting more code, or PM'ing me if you want... I could pm you my MSN if that'd be better...

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Thanks for all the help, dartsman. I greatly appreciate it! Here's the latest version of my function (within the class I've been working with). As I said, it worked fine when moved the code to another system. I'm just perplexed. Thanks for pointing out the "code" tag, by the way.

    int createArena(int startx, int starty, int onwall)
{
if( (startx < 1) || (startx > 78) ) { return 1; }
else if( (starty < 1 || starty > 58) ) { return 1; }
int countx = 0, county = 0;
switch(onwall)
{
case 0:
{
// The North wall of this room attaches to the above room.
// Check the area for space for a box room.
//startx = startx - generateNumber(2,3);
for( county = starty ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 8) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
}
break;

case 1:
{
// The East wall of this room attaches to the room to the right.
// Check the area for space for a box room.
startx = startx - 8; starty = starty - generateNumber(2,3);
if( (startx < 0) || (startx > 78) );
else if( (starty < 0 || starty > 58) );
for( county = (starty - 1) ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 7) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
}
break;

case 2:
{
// The North wall of this room attaches to the above room.
// Check the area for space for a box room.
for( county = (starty - 1) ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 8) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
}
break;


case 3:
{
// The North wall of this room attaches to the above room.
// Check the area for space for a box room.
for( county = (starty - 1) ; county <= (starty + 8) ; ++county )
{
for( countx = (startx - 1) ; countx <= (startx + 8) ; ++countx )
{
if(layout[county][countx] != 2)
{
// If there is insufficient space, return 1.
return 1;
}
}
}
// Otherwise, create the room.
// Prior to beginning the loop, set the switch variable to 0.
buildArena(startx, starty);
}
break;

default:
{
// The room is the central room, and has no immediately joining room.
// Thus, there is no need to check for space.
buildArena(startx, starty);
}

}
return 0;
}

I've tried to implement everything everything that has been suggested. As I've said, this compiled and executed as desired when I moved over to a command-line system. However, nothing changed in my graphics code (SDL) to have made a difference. There's something weird going on when I have this code in place. If I comment out all but two of the cases, then it runs again. Sometimes, technology perplexes me.

Thanks again for the help. You really don't have to worry about this, anyone. I was just hoping that there was some obvious error that could be pointed out.

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
what size is layout? what is it defined as?

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
I assume that "layout" is referring the the two-dimensional array called "layout." The integer array is 60 x 80 (so that when looking at it as a map, it's 80x60, however, since C is row-major). I'm not sure exactly what you mean "what is it defined as," but when I set it up, I just used a basic, statically allocated form of "int layout[60][80]".

Are those the answers to your questions?

I just can't understand why it works so long as there are not more than two cases. Much less why this switch has that issue when the switch used in the method before it (which this is nearly identical to) works just fine.

Oh, I forgot that my comments were all a mess in my code. Sorry about the confusion those comments may cause.

Thanks again for trying to help me with this. It's perplexing to say the least. It's so troublesome that I was inspired to create "The Programmer's Code." PyWeek 4 just began, so, for better or worse, I won't be able to get back to this project until PyWeek is finished.

Once more, thanks for any insight you may have. Thanks for continuing to try to help me.

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
yes, yes they were... though they didn't need soo much detail, the layout array was the only variable/function/'logical thing' I would think I was asking about...

I think you havn't actually defended properly against the array being accessed out of the bounds...

all you do is:
if( (startx < 1) || (startx > 78) ) { return 1; }
else if( (starty < 1 || starty > 58) ) { return 1; }

but then you do:
for( county = starty ; county <= (starty + 8) ; ++county )

what stops starty being 58? then doing:
county = 58
county <= (starty + 8) // ie 58 + 8 = 66
then accessing element layout[66][x]? if x could be from 1 -> 78, your definitely accessing outside once you do layout[66][78]...

You should create a function called 'GetLayoutValue()' or the like which takes an X and a Y value, and then within that function do the check (make sure its within the bounds of the array), and if so return the value at that position, otherwise return -1 or some default 'error' value. That way you will be certain that it isn't crashing because of a possible out of bounds accessing...

Also if Code::Blocks has built in debugger, then set a break point at the start of your program (first line in main() would be good) and then just step through your program, line by line, checking the values of that line (such as hovering over the variables to follow whats happening in the code)...

Finally, you might want to just write your code down on paper (not all of it, just this function and some others if required), and then follow it with some test values. Try inserting some bad values which you know will crash, and then some safe values. Follow the flow of your program and the data being passed through...

Anywho, hope that helped...

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Dartsman, you present an awesome idea with the function. For some reason, I didn't think to do that. I'll work on it when I get a chance.

Your help is appreciated as always!

------------------
Portal with information on my programming projects and links to my other work

dartsman

Member

Posts: 484
From: Queensland, Australia
Registered: 03-16-2006
np, let me know how it goes...

------------------
Junior Programmer www.auran.com
Quality Assurance Lead www.rebelplanetcreations.com

Xian_Lee

Member

Posts: 345
From:
Registered: 03-15-2006
Well, I haven't touched this program in a month and a half, but maybe I'll try forgoing sleep sometime this week and get back on it. My efforts have been in C# (and Torque) lately, and my C++ skills are probably atrophying as a result. I need to get back in the swing of things. When I do, I'll let you know how that function turned out.

Thanks again for all that help!

------------------
Portal with information on my programming projects and links to my other work