(I know you want to, ninja)
Well, teach me. I have a compiler and I have basic knowledge, but I'd like to know more before I decide to take courses.
Printable View
(I know you want to, ninja)
Well, teach me. I have a compiler and I have basic knowledge, but I'd like to know more before I decide to take courses.
int main()
{
int a, b;
int result;
a = 5;
b = 4;
a = a + 1;
result = a - b;
cout <<result<<endl;
}
It might look really confusing at first, but when you actually sit down and read it slowly, it's pretty easy to understand.
In the code I provided, I'm saying that a = 5 and b = 2, then I'm taking a and adding 1 to it, then taking the new answer of a and subtracting it from b which would give me 2.
I just started learning yesterday :3
I'm using code::blocks for my C++ writing along with the www.cplusplus.com website.
Should I learn C or C++ first?
I'm learning C++ to learn how to make my own game engine. I don't really know anything about C.
either, really
they're 80% the same
(C++ started out as an extension to C)
depends if you prefer procedural or object orientated programming
Well, it depends on what you want to do with it. C++ is better for large projects, while C is best if you're writing time-critical applications. C would also be the logical choice if you want to make other things than computer programs, like if you want to program other integrated chips.
Many hold that you should always learn C first and then move on to C++, as C++ almost is a superset of C, but either way knowing one will help you with the other.
:wtf: Arrays are exactly the same in C and C++.
He's right about the right and wrong ways being different in C and C++
Critical section in C
Critical section in C++Code:void CriticalMethod(void){
pthread_mutex_lock(somelock);
//some critical stuff
if (boolean){
pthread_mutex_unlock(somelock); //have to unlock in every exit path
return;
}
//more critical stuff
pthread_mutex_unlock(somelock);
}
Code://Autolock.h
struct AutoLock{
public:
AutoLock(pthread_mutex_t * lock){
pthread_mutex_lock(lock);
mylock = lock;
}
~AutoLock(void){
pthread_mutex_unlock(mylock);
}
private:
pthread_mutex_t mylock;
}
Code:void CriticalMethod(void){
AutoLock lock(somelock); //will automatically unlock when it returns
//some critical stuff
if (boolean){
return;
}
//More critical stuff
}
***********************
What exactly would you like to know guitarboy, honoured you came to me :D
I learned C first, then taught myself C++. I would recommend just learning C++, most programming is done in C++, and it's a lot easier. It's also a good thing to understand object oriented programming.
Here's some things to understand, in order
Primitive types: int, long, float, char
Scope
methods and functions
pass-by-reference vs pass-by-value
const
Pointers
Objects (classes and structs)
Constructors and destructors
Feel free to IM me about anything :D
I know they are the same
but they're hailed in C, and frowned upon in C++
From the man himself
http://www2.research.att.com/~bs/bs_faq2.html#arrays
Oh, okay, you meant that in C++ you're supposed to use STL containers :P We still use arrays for various things though.
Actually I have a question...
I'm learning C++ and right now I'm reading about ++ and --
The example it gives me is this...
Example 1:
Example 2:Code:B=3;
A=++B;
// A contains 4, B contains 4
I don't really understand the whole ++ and -- and how it affects the A and B variables. Can someone explain how it adds up?Code:B=3;
A=B++;
// A contains 3, B contains 4
Edit: Also, how does all this make up a video game engine?
increment and decrement
(Ie. add one, or subtract one)
used all the time when looping and keeping count of things
a++ means "return the value of a, and then increment it"
++a means "increment a, then return the value"
subtle (but important) differences, however the differences between the pre & post incrementation are only important if you care about the value of a variable mid-operation
andCode:for (i = 0; i < max; i++)
{
}
are identical in operationCode:for (i = 0; i < max; ++i)
{
}
(because we do not care about the value of 'i' mid-operation
however,
say we are keeping a count of something that we later need to step back through in reverse
here, we do care about the value of var mid-operation, therefore we store the "old value" of var and increment varCode:void increment_something(int var)
{
old_var = var++;
}
You can of course do this
then we've split the operation into twoCode:void increment_something(int var)
{
old_var = var;
var++;
}
and now we no longer care about the return value of the increment
Almost correct. In for loops you want to do the latter because in order to return, then increment, it has to keep a copy of it. Not a problem with ints, but with objects it can.
++ and -- are weird to learn.
b = ++a; is like this:
a = a + 1;
b = a;
b = a++; is like this:
b = a;
a = a + 1;
:)
Err...you're using some things in there I haven't learned yet. So I think you just made it more confusing for me...
Edit: Ok that makes it a little easier to understand...
So would it be something like this for the 2nd part?
b = 1;
b = a++;
Would the result be: b = 1, a = 2? Because I already defined b to equal 1 and then a equals b which is 1, then I add a to a to get 2, right?
follow a tutorial on C++
I've always liked this one
http://www.cprogramming.com/tutorial/lesson1.html
It'll take you through the basics, and slowly build up to more complex things
*edit*
Just realised you're not the OP.....
Lol no I'm not :P
But I'll make good use of this thread...
Also, I'm following this tutorial so far: http://cplusplus.com/doc/tutorial/operators/
edit: but again, how does all this make up a video game engine? Or any program?
Well, we break it up. We break down the seemingly huge task of a full program and break it down into pieces which are more manageable. We then code each part, sometimes sticking the together in one executable, but more commonly, we create a complex set of dynamic libraries.
A video game engine would probably be about a quarter of a million lines of C++ code, broken up into maybe 1000 different files.
Wow...quarter of a million...
Well I guess that adds up fast seeing how small lines of code are.
A Roxxor wants me to make a simple text based game. I'm not sure how I'm going to do this...
Well, Most of use consider lines of code as actually newline characters, including white space and comments.
What kind of game?
hangman is always a good first game
pick a random word from file of possible words
let the user guess letters
print letters found, and underscores for not found
keep a count of num guesses
Just a simple text based game. Maybe something like, "You grab a gun. What do you do next? Respond: Shoot the enemy. The enemy dies."
I'm not really sure if that's how it's going to be though...
I'm wanting to make my own game engine and A Roxxor said he would help me out. We're going to be working on a 2D side scrolling platformer. I have all the ideas in my head and some of it's written down.
I think he said he's going to be working on the level editor and I'll be learning C++ and helping Drawsher with working on the sprites for the characters.
Oh oh oh, I'm doing that too. :D I'm calling my game Mavio. I've got the shell of it all done, I just need to fill in my code out with the functionality :)
the way to plan out a programming project is to start with a large idea and break it down into lots of smaller segments
then break those segments down further, and so on
You should end up with tons of really simple operations that are a doddle to code
Code:void player::take_damage(int damage)
{
player.health -= damage;
if (player.health < 0)
{
died();
}
}
So far all I've learned how to do is this:
http://img503.imageshack.us/img503/2765/67539020.jpg
Which comes out to be this:
http://img99.imageshack.us/img99/6329/69704121.jpg
Good start, maybe the next thing you can learn is how to save your screenshots in pngs instead of jpgs :P
Ynot speaks the truth, a good design is paramount to success, every detail should be worked out before any code is written. Here is the design for the side scroller that I've started, I'll probably write it this weekend:
Spoiler for Top Down Design:
Thanks guys.
I'm going to learn C++ first, then maybe C. Oh, Ninja, what compiler/text editor do you use? I'm using code::blocks, but I also have xcode though it's more confusing. Which do you suggest?(I'm asking you because I now you're an apple guy ;))
Not really, because I've mapped it all out, I think it will be fairly easy, each of those components shouldn't take more than 50 lines of code.
C / C++ is platform independent, so it has no support for windows natively. You have to use an external library. This could be X11, GTK, Windows API, wxWidgets, Qt, or GLUT. For games, GLUT is the easiest choice because it's an extension on OpenGL. GLUT is also the easiest for a beginner because it's C based, therefore there is no complex C++ functionality like Templates and inheritance and stuff.
Allegro and SDL can both be used in C++, however, OpenGL has been the graphics standard for 15 years.
I use Code::Blocks when I'm writing code on Windows or Linux, and XCode and Code::Blocks when writing code on OSX. Code::Blocks is far simpler, however XCode is the most powerful IDE out there. So what I do for big projects is I write small components in XCode and use all of XCode's debugging tools and such to make sure it's right, then put them together in Code::Blocks.
How exactly do I draw an image onto the screen?
And I found a tutorial for making a window. I'm not sure if it was just the tutorial, but there is a butt load of code involved for making something as simple as that. You'd think it'd be easier right?
I'm not a graphics guy (I hardly ever program GUI apps)
but using ninja's sugesstion of GLUT
here's sample code from a Glut tutorial
This will open up a window, 320x320, with a triangle in itCode:#include <GL/glut.h>
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glVertex3f(-0.5,-0.5,0.0);
glVertex3f(0.5,0.0,0.0);
glVertex3f(0.0,0.5,0.0);
glEnd();
glFlush();
}
void main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(320,320);
glutCreateWindow("3D Tech- GLUT Tutorial");
glutDisplayFunc(renderScene);
glutMainLoop();
}
*sigh*
I think I'll just go back to learning lines of text and numbers...
Don't be intimidated, it's really quite simple if you know what each command does. Follow the path of the code, it always starts at main, and I've put comments around the OpenGL and GLUT stuff explaining what each function does. :)
Code:#include <GLUT/glut.h>
void renderScene(void) {
/*
glClear erases what's already stored in the drawing area,
GL_COLOR_BUFFER_BIT is the colour to restore it too, by default, it's black
*/
glClear(GL_COLOR_BUFFER_BIT);
/*
We want to draw a triangle, so tell OpenGL that the next drawing functions that we are doing
should be done in triangle mode
*/
glBegin(GL_TRIANGLES);
/*
These are the verticies of the triangles, now with the default setup on the window, the window is 1x1, so
the coordinates are in relation to that.
*/
glVertex2f(-0.5,-0.5);
glVertex2f(0.5,0.0);
glVertex2f(0.0,0.5);
//This tells OpenGL that I'm done placing my coordinates and that it can draw it
glEnd();
/*
This one is also pretty complicated, OpenGL buffers it's drawing commands for optimization purposes
this glFlush command tells OpenGL that there are no more commands to come, and that it can go ahead and
finish drawing whatever's still in the buffer
*/
glFlush();
}
int main (int argc, char ** argv){
/*
This line initialized GLUT, which is the window engine and the interface to OpenGL
Internally, it loads the libraries and sets everything up
*/
glutInit(&argc, argv);
/*
This sets the initial display mode for OpenGL
GLUT_SINGLE means that it's using a single drawing page, so everything that gets drawn goes directly onto the screen
games should be double buffered to elimiate flickering
GLUT_RGBA tells glut that the pixels will be rendered in Red, Green, Blue, Alpha order
*/
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
//These should be obvious, they're setting the window's position
glutInitWindowPosition(100,100);
glutInitWindowSize(320,320);
//Creates the actual window
glutCreateWindow("3D Tech- GLUT Tutorial");
/*
This is a little advanceds, this is registering what's known as a callback function. GLUT basically needs to know what do it
if it's in a situation where it needs to draw. This could be the intial render, or of another window is moved over it, or if
it's resized. glutDisplayFunc is given the name of the method that glut should call when it needs to redraw
*/
glutDisplayFunc(renderScene);
/*
Start the main loop :)
*/
glutMainLoop();
return 0;
}
Indeed,
first learn the language, then do something small and easy to get the hang of things
You've just started on your journey as a bridge-builder
Your ultimate aim is this
http://secretperson.files.wordpress....n-bridge-l.jpg
but you've got to start off building a few of these first
http://www.freeimageslive.co.uk/file...46.preview.jpg
I agree, you saw my design right? Mario is a fairly simple game, yet it's quite a lot of classes and functionality. I could probably knock it out in a day, but I'm very experienced.
I guess I made my first game!
Simple if/else statement set up.
If you enter the number 3, you win! But if you don't, then you lose!Code:#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Please enter the number 3: ";
cin >> a;
if ( a == 3)
{
cout << "You have entered the right number!";
}
else
{
cout << "You lost the game.";
}
return 0;
}
How would I set it up so it repeats the first line of code?
I want to set it up so that if the player enters the wrong number, then it goes to repeat the "Please enter the number 3" part. Or, if they get it wrong, then it asks for the player "Do you want to play again? Y/N" and if they enter Y then the whole thing repeats itself, or if they enter N, then the game exits.
You need a loop. C++ has a number of loops, but the one that you want is the do/while loop :) Basically it's saying do {this code} while (this is true)
Code:#include <iostream>
using namespace std;
int main()
{
int a;
char cc;
do {
cout << "Please enter the number 3: ";
cin >> a;
if ( a == 3)
{
cout << "You have entered the right number!";
return;
}
else
{
cout << "You lost the game." << endl << "Would you like to play again? Y/N";
cin >> cc;
}
} while (cc != 'Y');
return 0;
}
although I'll leave you with thisCode:#include <iostream>
using namespace std;
int main()
{
int a;
bool correct = false;
char play_again;
while ( ! correct )
{
cout << "Please enter the number 3: ";
cin >> a;
if ( a == 3)
{
correct = true;
cout << "You have entered the right number!" << endl;
}
else
{
cout << "You lost the game." << endl;
cout << "Play again? (y/n): ";
cin >> play_again;
if ( play_again != 'y' )
{
correct = true;
cout << "Thanks for playing." << endl << "Goodbye!" << endl;
}
}
}
return 0;
}
The above is not very clear to read (it's all in one function)
your job (when you get far enough along with the language) is to clean this up with a much simpler program flow
*edit*
beaten to it
What does the "char" do?
it's the character datatype
meaning it stores a single character
a sequence of character datatypes "strung" together is where the word "string" comes from
Edit: Never mind. Note to self: Learn to see if there are more pages.
But yeah, I also support you doing some smaller projects first.
Have you given any thought yet to C#?
C is pretty much dead except for embedded solutions, C++ is still a great language and supports object oriented design, but with modern hardware, all but the most time critical tasks can be handled with C#. You also have the ability to call C++ unmanaged code from within wrappers if you have a section that needs to execute at it's fastest.
My suggestion for a compiler is Visual Studio 2005 or 2008 (2003 is OK, but doesn't support the .NET 2.0 framework well). I've been using the Microsoft Cxx compilers since they were introduced and really like it. In fact I'm using VS2005 as we speak.
C# is generally just used for Windows exclusive applications, though, and they require the .NET network to run. It's harder to write cross-platform applications. It's not as elegant at making native applications, though you're saved from hunting for external libraries or writing system-call wrappers yourself.
I thought C was commonly used for time-critical operations still, such as graphics modules.
I do however agree that Visual Studio is an excellent set of coding tools. I use VS2008 professional myself (no, it's not pirated... but neither is it bought).
Even unsafe C# code doesn't run as quickly as C++.
It's also very heavily dependent on the Windows runtime libraries. I think C# is an atrocious attempt at making C++ more like Java. C and it's derivatives are not meant to be safe, they're meant to do exactly what you tell them to do.
Wow...
I think I'm going to attempt to start learning C++ again...
I gave up pretty darn quick last time. Mostly because I was trying to get code::blocks or something and it wasn't working... is code::blocks like a plugin to microsoft visual C++ or something?
In fact, talking of which, is microsoft visual C++ the right thing to use?
EDIT: Hold on... is code::blocks entirely seperate from windows visual?
code::blocks has nothing to do with MS
It's a cross-platform IDE for C & C++
I wouldn't get too hung up on IDE's to start with
Just code in a decent text editor (eg. Vim) and compile on the CLI
Ah yea, I had a look around google just there.
And... hrm... by the way I see it, I would rather use code::blocks.
I don't want to have to end up changing what I use once/if I get better at it. Besides... code::blocks looks more appealing than vim, and less complicated looking.
Code::Blocks is great, it's what I use professionally on Windows and Linux. And it does all the complicated linking crap for you.
Cool, I have downloaded and installed code::blocks. Then it asked me what compiler to use, so I used windows visual C++ since it was already on my computer from last time I tried all this stuff.
My problem now is that it won't build or something, I click build, then I click run, and it says I need to build it. I then tried "build and run" and it just kinda does nothing. Don't know what the fuck is wrong here.
Got my loop set up so that if a doesn't equal 10, then it keeps adding to it until it does. Pretty neat stuff right there :3Code:#include <iostream>
using namespace std;
int main()
{
int a;
a = 0;
if ( a < 10 )
{
do
{
cout << a << " Adding one." << endl;
a++;
if ( a == 10 )
{
cout << a << " is the right number!" << endl;
return 0;
}
} while ( a < 10 );
}
}
Fixed my problem, thanks to A Roxxor ;)
Now time to learn that bastard of a language :P
Also, nice one slayer.
Here's another version of what slayer posted:
Just to add some more to study :pCode:#include <iostream>
using std::cout;
using std::endl;
int main (void) {
int a = 0;
while (a < 10) {
a++;
}
cout << "Congrats, the variable <a> hit 10!" << endl;
return 0;
}
What's the difference between C++ and dev C++
Dev-C++ is a deprecated IDE, it's not a language or even a compiler. It uses the GCC compiler. The project was discontinued and merged with Code::Blocks.
Cool :) But you don't need that first if statement. You just assigned a to 0, there is no reason to check if it's less than ten since you know it will be :)
But it doesn't really matter if you do, though. It's only one extra comparison. The place you really want to use a do...while is where you need to run the data through at least one literation before you're even ready to test the condition (can't think of such a scenario of the top of my head, though).
Also, instead of writing
Why not just writeCode:int a;
a = 0;
Uses less space and is actually a bit faster.Code:int a = 0;
returns 7 errors fix it dreamviews!Code:#include <isostream>
using namespace std;
int main()
{
int a, b, total;
cout << "Enter two numbers here...;" << endl;
cin >> a >> b;
total= a + b;
cout << "Sum equals;" <<Total << endl;
system(PAUSE) ;
return 0;
}
Emmmm... doesn't that basically the actual code with :
?Code:int main()
{
return 0;
}
I'm guessing that is some sarcastic way of saying his program can't be fixed?
Ok, I fixed it. Suck it, Ynot :P.
Code:#include <iostream>
using namespace std;
int main()
{
int a, b, Total;
cout << "Enter two numbers here...;"
;cin >> a >> b;
Total= a + b;
cout << "Sum equals;" <<Total << endl;
return 0;
}
I had no idea what I was doing, but it somehow worked :)
Yeah, C++ is case sensitive.
It's supposed to be <iostream>, not <isostream> (input/output stream)
Edit: The compiler will also output which lines and expressions were making the trouble. Compiling that you'd first get an error stating that <isostream> couldn't be included in the project, and the subsequent errors came because std::cout and std::cin wasn't defined (the <iostream> header defines these values so you can use them)
I don't understand what it wrong with this. It says "error: expected primary-expression before "else"" and also "error: expected ';' before else"
It is supposed to be that it calculates the radius or circumfrence of a circle if you input the circumfrence/radius.
Have I done something wrong with the if/else thing?
EDIT: Fixed it, but there is something wrong somewhere in it, even though it runs... I'll need to find that.Code:#include <iostream>
using namespace std;
#define PI 3
int main()
{
double r, d, circle, entered_number;
cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;
if (entered_number == 1)
cout<<"To find circumfrence of circle, please input radius"<<endl;
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;
else if (entered_number == 2)
cout<<"To find radius of circle, please input circumfrence"<<endl;
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
return 0;
}
EDIT2: found that problem too... a very obvious one :P
you've forgotten to group the code propperly. What you wrote is basically
When you wantedCode:#include <iostream>
using namespace std;
#define PI 3
int main()
{
double r, d, circle, entered_number;
cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;
if (entered_number == 1) {
cout<<"To find circumfrence of circle, please input radius"<<endl;
}
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;
else if (entered_number == 2) {
cout<<"To find radius of circle, please input circumfrence"<<endl;
}
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
return 0;
}
If you want more than one block of code after an if/else/for/while/whatever statement, you need to enclose it in brackets. Also, it's common to indent blocks so that the end result looks like this (but it's strictly optional, C/C++ ignores excess white space)Code:#include <iostream>
using namespace std;
#define PI 3
int main()
{
double r, d, circle, entered_number;
cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;
if (entered_number == 1) {
cout<<"To find circumfrence of circle, please input radius"<<endl;
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;
} else if (entered_number == 2) {
cout<<"To find radius of circle, please input circumfrence"<<endl;
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
}
return 0;
}
Makes the code much cleaner, as you can see.Code:#include <iostream>
using namespace std;
#define PI 3
int main()
{
double r, d, circle, entered_number;
cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;
if (entered_number == 1) {
cout<<"To find circumfrence of circle, please input radius"<<endl;
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;
} else if (entered_number == 2) {
cout<<"To find radius of circle, please input circumfrence"<<endl;
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
}
return 0;
}
Yea, I had it all fixed up like that. And yea, all my indents went away while editing it so much, deleting, adding in stuff, I ended up deleting all the indents.:P
I could make the program much better than that, but right now, I'm just using it as a learning thing. Next thing to try is to use the loop thingy (do while?), so that the program stays open and you can calculate more.
You should also loop into while loops and for loops.
Code:int a = 50;
do{
std::cout << "I'm inside the loop " << a++ << std::endl;
} while (a < 10);
Have one but very important difference, see if you can figure out what it is :)Code:int a = 50;
while (a < 10){
std::cout << "I'm inside the loop " << a++ << std::endl;
}
Well, one of them is a while loop, and one is a do while loop. I don't really understand the difference, even after reading about it.
I should look at this page on loops for ages. I have trouble taking in/reading that much information at once, mainly because of a short attention span. I'll just have to try...
Thanks, slash.
How do I run it in a window instead of terminal?
Yea... I was wondering the same thing.
I want to learn how to make a GUI. It isn't necessary at this stage though, anyway.
The difference has to do with where the check is made. In the first bit of code, the check doesn't happen until after what's inside the loop has been done, therefore, it ALWAYs gets done at least once, the second piece of code does the check beforehand, so it may never get called :)
Stick with terminals for now, I'll show you how to make a window a little later. :)
alright, I wrote a program that gives you the circumference of a circle after you put in the circumference and the approximate of pi.
How can I make it simpler, i.e; tell it that the variable p is 3.14, without you having to put it in.
and how do I run it in a window, not terminalCode:#include <iostream>
using namespace std;
int main()
{
int r, p, Total;
cout << "Enter radius and pi approximate here... "
;cin >> r >> p;
Total= r * r * p;
cout << "Circumference is " <<Total << endl;
return 0;
}
First off, ints are just integers, you need decimals for this, so we use float instead. Also, your formula was wrong :P Circumfrance = pi time diameter, you were calculating area. lol.Code:#include <iostream>
using namespace std;
#define PI 3.141592654357
int main()
{
float r, Total;
cout << "Enter radius here... "
cin >> r;
Total= r * 2 * PI;
cout << "Circumference is " <<Total << endl;
return 0;
}
#define is what's called a macro, it's not real code. When the compiler compiles your source code, the first thing that it does, it copies and pastes macros. So when the code gets compiled, the literal value of pi gets replaced at all occurrences of PI. It is standard practice to keep definitions in caps, although not necessary. :)
Nice, guitarboy. It's funny how different I would do it from that. It's amazing the amount of possibilities for one single purpose.
Also, you don't really need a window yet, do you.
radius * radius= diameter, times pi :P
Quote:
#define is what's called a macro, it's not real code. When the compiler compiles your source code, the first thing that it does, it copies and pastes macros. So when the code gets compiled, the literal value of pi gets replaced at all occurrences of PI. It is standard practice to keep definitions in caps, although not necessary. :)
it would be nice to know how to do it.Quote:
Also, you don't really need a window yet, do you.
And color it.
and change text color.
etc.
:)
Lolfail :P
I had it in my program. I had defined PI to be 3 because I was lazy, I never did it exact because it was only for testing purposes. But yea, formula was: cirumfrence = PI * r * 2 and for radius I had r = circumference/(r*2).
All I did was let the "user" input the circumference if they wanted radius, or input radius if they wanted circumference.
I understand why you want to get into GUI stuff, but trust me, at this stage it'd just confuse you
You've got to get a proper handle (no pun intended) on the language before delving into external APIs
At present, you're doing really simple maths with C++
you've yet to grasp the more advanced concepts needed for GUI apps
We haven't even covered stuff outside main() yet
let alone classes, templates, memory allocation, STL, etc. etc.
Walk, then run
But right now, we're still bobing about in the sea, before we developed legs
:lol: I get it :D
Now lets do methods, this program how two methods, one for area, and one for circumference, and the user gets to decide which to use.
Code:#include <iostream>
#define PI 3.14159
float Circumference(float r){
return r * 2 * PI;
}
float Area(float r){
return r * r * PI;
}
int main(){
//Get the radius of the circle from the user
float radius;
std::cout << "Enter radius." << std::endl;
std::cin >> radius;
//Get the function wanted
std::cout << "\nPress 1 to Calculate Circumference.\nPress 2 to Calculate Area" << std::endl;
int option;
switch (option){ //kind of like a fast if / else
case 1: //do if option == 1
std::cout << Circumference(radius) << std::endl;
break;
case 2: //do if option == 2
std::cout << Area(radius) << std::endl;
break;
default: //neither of the other options
std::cout << "Error, you didn't input one or two" << std::endl;
}
return 0;
}
Alright.
Whhat should I learn next, then? Youtube lessons are not my friend.
what is the std::--- for?
Why not just cout, int etc.
Hmm... how to describe how namespaces work :? That's not important right now (and an odd concept before learning classes,) you can use cout simply and add a using namespace std at the top of the program.
Basically, there are multiple couts and the compiler has to know which one to use. std:: tells it to use the std one, you did that in your program by defining that the entire program uses std. Here's a little demonstration of namespaces.
Weird, I know, but very useful for more advanced programming, for now you can forget what I just said :PCode:#include <iostream>
using namespace std;
namespace Integer{
int var = 5;
}
namespace Decimal{
double var = 3.1416;
}
int main () {
cout << Integer::var << endl;
cout << Decimal::var << endl;
return 0;
}
Why isn't this working? It says I need } at the end, but I did...
Code:#include <iostream>
using namespace std;
int main ()
{
int x = 3;
int y = 4;
if (x > y)
{
cout << "X is greater then Y " << endl;
}
else
{cout << "X is less then Y " << endl;
system("PAUSE");
return 0;
}
Those are methods. That's how you do things multiple times, you can keep calling that as many times as you want. Everything is done like this, even << in cout is kind of a method.
\n is just a newline character, it's the same as endl, but can go inside of the quotes, I just did it to save space.
You have a stray bracket before the last cout, you never close it. :)
Well, namspaces do use the same delimiting syntax as class methods, so I think an understanding is helpful
Namespaces
Note the #include line,Code:#include <iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 0;
}
we're pulling in external code
specifically, code to allow input / output of data using streams
There's loads of external code you can pull into your program to acheive common tasks
because of this, it's important to separate code into "namespaces"
Say we are making a program that tracks finances of a company
We could define a couple of classes in our program to track money incoming and outgoing from our company
We may call these classes "cin" for cash in, and "cout" for cash out
but we'd have a problem - these names clash with the names defined in iostream for input & output to the standard streams
For this reason, any "standard" external code (Ie. comes with all compilers and is expected to be present) is separated off into it's own namespace, called "std"
This brings us to the second line
using namespace std;
is asking the compiler, should it come across something not defined in our program's namespace, to look in the standard namespace for it
You can omit the "using namespace std" line, and append the std namespace to object calls
The above can be re-written to this
So, namespacesCode:#include <iostream>
/*
* we don't need this line anymore
* as we're using absolute referencing
* for std objects
*/
// using namespace std;
int main()
{
std::cout << "hello world" << std::endl;
return 0;
}
just a way to separate out definitions so code from different sources don't clash with each other
\n doesn't flush the stream
\n is just a character, and therefore cannot "do" anything
Ynot's right, \n does not flush the stream.
This is why \n is useful for inside of a string, it allows you to keep buffering it instead of having to wait for the buffer to be flushed.
Well, SOMETHING is flushing the stream, because when I run:
I get "Thingger1" displaying immediately, then it pauses for a second, and then Thingger2 displays. This has consistently been my experience for years and years. If it didn't flush the stream, it would have paused a second and then displayed both lines at the same time. So, what's happening here if not flushing? It might be the lower level stream operations that happen under the hood, but you can't deny this behaviour. :)Code:#include <iostream>
#include <unistd.h>
using namespace std;
int main(void)
{
cout << "Thingger1\n";
sleep(1);
cout << "Thingger2" << endl;
return 0;
}
EDIT to add: Did some googling, and it seems that this is dependent on the compiler. I suspect cout is special in that behaviour, and other streams (fstream, etc.) don't do that. Back in the C days, it was the same story with '\n' and printf.
\n isn't flushing the stream, in most compilers, the stdout streams aren't buffered because there is boatloads of memory and speed to burn. But you're not guaranteed to get that result all the time. Try it with file i/o and see what you get :P
Just remember there is a difference between what a compiler will do and what the C++ Standard states.
Case and point:
The C++ Standard states that sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long), but it's perfectly legal for them to even be the same size.Code:if ((sizeof(char) < sizeof(short)) &&
(sizeof(short) < sizeof(int)) &&
(sizeof(int) < sizeof(long))){
cout << "Expected" << endl;
} else {
cout << "Reality on most compilers" << endl;
}
I have a question.
In this program, when you input two words, (i.e. first name and second name) it only takes the first word. I read somewhere in the tutorials of a data type that takes in any amount of words, rather than one. But I can't seem to find it. In fact, I'm not even sure if it was to do with data types or not.
But anyways, yea, how would I allow for two words to be input?
Code:#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string question = "What is your name? ";
string greeting = "Hello, ";
string yourname;
cout << question << endl;
cin >> yourname;
cout << greeting << yourname << endl;
system ("PAUSE");
return 0;
}
standard streams are whitespace delimited (unix convention)
use getline() to get an entire line (up to newline char)
btw, what's this system("PAUSE") thing?Code:#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string question = "What is your name? ";
string greeting = "Hello, ";
string yourname;
cout << question << endl;
getline(cin, yourname);
cout << greeting << yourname << endl;
system ("PAUSE");
return 0;
}
Oohhhhhhhh... Thanks.
system("PAUSE") means that when I run the program, it doesn't close as soon as it finishes. But it lets you close it by pressing any key.
Within the programing software stuff it isn't an issue, but when it is the .exe on it's own, when you run it, it would close the moment you finish inputing stuff.
Code::Blocks automatically pauses the execution at the end for you, you don't need that unless compiling or running outside of the IDE :)
How to I package together my code into an exe or something both windows and macs can open?
Don't do that
I'm not sure exactly what you mean by "closing" (you mean the terminal window?)
but good programs finish as soon as they're done, and do not hang for user input unnecessarily
Say you release a program that takes input from stdin does something and outputs to stdout, exiting 0 on success and any other value on error, errors get sent to stderr
I would like to be able to say something like
orCode:slash112_program || echo "Error $?"
hanging the program for input at the end breaks program flowCode:cat some_file | slash112_program | less
anyway....
You can't (well, you can, but it's way more trouble than it's worth)
Either make the various platform & architecture packages yourself
or the easy route - just release the code
If the program's useful, people will package it up for their platform / architecture of choice
It does that for you :)
Go to the folder with your Code::Blocks file, then go to bin/Debug. A .exe file should be in there :)
If you use standard C++, it will compile on any platform with no change in code :D Firefox compiles on every major platform, using the same code, with very little preprocessor.
"C++ will let you shoot your foot without warning you. In fact, it will even load the gun for you."
~ Allegro User
Ynot. I'll give you an example. If the program asks you to input something, you would put it in. You would get an instant response, and then the terminal window would instantly shut the moment after the new text is displayed. This is not what you want.
It's not that I need it at this level, I don't need any fancy way of closing the program at this level. It is just purely for having it there.
There are a lot of things you need system calls for, though, like GUI and scanning directories and such. So Firefox must be using preprocessor directives, or libraries which uses them.
Console programs are normally opened from the terminal, though. And if you do that, then the terminal doesn't close and you'll see the output. It's just if you open it by double clicking on the executable that you won't see the text, but then that's no how the programs are supposed to work. If you want those kinds of programs you need GUI.
Funny thing, I've got C++ as a university subject this year. Of the things we'll learn this year, there was only one thing I haven't done before.
I said little preprocessor. I've looked at the Firefox code because I reverse engineered a chunk of it. All of this stuff uses a NPWindow object, almost all of the preprocessor is in there.
But stick with the terminal while learning, GUIs can be a pain.Quote:
Console programs are normally opened from the terminal, though. And if you do that, then the terminal doesn't close and you'll see the output. It's just if you open it by double clicking on the executable that you won't see the text, but then that's no how the programs are supposed to work. If you want those kinds of programs you need GUI.
But I'm sure that you'll learn better technique and optimization techniques that you currently don't know. :) Assuming the professor is competent, I had a professor in college who was a good C++ programmer in 1995, but he stuck to those techniques, so we were taught no modern designs. C++ coding changes very quickly, if you don't stay on top of it, you can fall behind quickly.Quote:
Funny thing, I've got C++ as a university subject this year. Of the things we'll learn this year, there was only one thing I haven't done before.
I can't wait till I get to GUIs. That will be kick ass.
C++ is a nightmare with GUIs because the language isn't designed for it. I just spent 3 full workdays creating a frame, a dynamic set of menus, a status bar, and a web preferences pane. :(
Luckily, there are graphical ways to do it in 5 minutes, which is what I recommend using when starting out. The only reason I don't use that is because I need more control over them.
Haha, wow.
But still... it would be worth it.
I applied to a computer games course which consists of programming in C++ (I think...) and 3d modelling. I want to get into that (although I applied to physics too, at the time I wanted that more)
But yea... I'm just learning this so I have a bit of knowledge before going there (If I get in)
Ah, okai.
Yeah, I know. I tried learning GUI a while back, but I simply gave up on it for a while. I didn't have a clue about what I was doing, or what the code elements meant or anything. Figured I'd just write a console program with some of the same functionality and port it when I was ready :p
Yeah, I hope so. There must be things I've missed, since I've mostly thought myself what I know. But I think he must be a good programmer, he's taught that specific course for the two year it's run, and he taught the Java course the engineers attended instead. He ought to be good by now.
Good Java Programmer != Good C++ Programmer, very different designs.
Also, almost all of your functionality can be done using the console. I'm currently tearing apart an application so that the functionality is completely disjoint for the main window. The window runs by itself and loads the functionality as a dll.
Yeah, I'm aware of that, but he's an experienced programmer, he's used quite a few different languages, so I'm guessing he'd want to teach the language properly. Also, he started introducing "best practise" rules the second lesson (accurate ones). That's a good sign.
If you have Ubuntu, I'll show you how to create a simple GUI program if you want. I can do it on Windows too, but I like using the wxWidgets library for that, and that's impossible to compile on Windows, I've tried and failed at that many times. I'm not looking forward to the next major release because I'm planning on recompiling it as a dynamic library.
wxWidgets works perfectly fine on Windows Vista... Code::Blocks with wxSmith does a lot of the work, but it's perfectly possible to code everything by hand with a wx Template.
Then you're lucky. wxWidgets is a very complex build, and it requires a lot of external libraries which do not come with the source. It's really annoying to build.
If I'm not mistaken all I had to do was download the source [I think there is a windows version or something...?] and then tell code::blocks where it was and it compiled it for me. Now all I have to do it fire up a template or use wxSmith ^_____
Here's a list of things to learn before tackling GUIs
methods
header / functional files
classes / structs
static vs dynamic methods
overloading methods
overloading operators
scope
pass by reference vs pass by value
polymorphism / inheritance
inline functions
macros
pointers
reference / dereference
casting
opaque pointers
callback functions
static libraries vs dynamic libraries
preprocessor
If you know those, then you know .01% of C++ :)
the other 99.99% is divided evenly between exceptions and trying to understand the Boost libraries.....
And STL :P
Hey Ninja, i dont know too much about programing and that type of stuff so 1 basic and dumb q.
What kind of applications do you most commonly use programming for? What possible uses does it have?
I think Soros was asking me specifically :P
I professionally write a variety of programs that revolve around our custom GUI format. It's basically a GUI engine, coupled with our database that allows us to build very complex gui apps and websites, really fast. I write the backend engine that runs the thing and communicates with the server.
I also write games from time to time if I'm practicing a new technique or something.
I was just wondering. How would you make it so that you just press a key and it would do something. For example:
if spacebar is pressed
cout << "OMG you pressed space!"
How would you code that first line? And would you need to set a variable for it?
Same with any key, like the left arrow key, or whatever. Just something where you press the key without having to hit enter too.
Well if you're using glut, you can register a callback for that. Otherwise, you have to have a loop that continually check for it.
:DCode:#include <pthread.h>
pthread_t keyboard_thread;
void * keyboard(void * argument){
char mychar = '\0';
while(mychar != 'x'){ loop until an x is pressed
fflush(stdin);
scanf("%c",&mychar);
switch (mychar){
case ' ':
cout << "Space bar pressed" << endl;
break;
}
}
return 0;
}
int main(){
pthread_create(keyboard_thread, NULL, keyboard, NULL);
//Do whatever you want
return 0;
}
That's threading though, which is a little more complicated.
That'll only get input characters, though, like space and a, b, c, (...). The arrow keys and enter and all of those won't be registered, right? Also, pthreads doesn't work on windows.
pthreads works on windows :P I use it all the time.
And yeah, then you use glut or another library with keyboard callbacks built in like wxWidgets or Qt or the Windows API :P
intercepting keystrokes is non-trivial
as it's highly dependent on the environment (including whether the input stream is buffered or not)
Best bet is to use a curses library
(that's what all the text adventure games use)
http://en.wikipedia.org/wiki/Curses_...ing_library%29
Jesus shitter, it sure is complicated for such a simple thing.
Well, intercepting keystrokes straight off the device isn't simple
The OS has hooks to the keyboard device, and you're overriding them
But the complexity of many things boils down to the desire to remain platform & architecture neutral
I'm sure there's a simpler Windows specific hook you could tap into to intercept keyboard characters, but then you're hamstrung to a specific platform
(and at the mercy of the platform to maintain the hook across future versions of the OS)
Hooks are abstracted, Windows can change them and the APIs should still all work fine. Oh, abstraction is something that should be added to that list that I made.
I have taken a bunch of different programing classes, and really the key is getting into the right frame of mind. Once you know one program its a lot easier to learn most others. Even entirely different programs use the same basic concepts.
I find that's true only if it's in the same paradigm. Knowing a procedural language it hard to go into a OOP language, and an assembly language is really weird. :P
That is probably true. The ones I have worked with is java and c++ which are very alike. And the oracle programing language which is used for databases and stuff, I forget what it is called but its a lot like them too. As is HTML, which is like an entirely different area making webpages and stuff, but interactive websites uses a very similiar method.
Also the small programs you download for like games and stuff. A lot of time they got their own languages for using inside the game(like games that lets you make maps and stuff). A lot of time they are based off this same type of stuff.
There can be big changes at time. But once you learn one it defenitly helps you with learning all the related ones.
Just js is a very very simple object oriented language. java and C++ are insanely complex and powerful.
khh, you are refering to scripting languages, I've written 5 of them myself for various reasons. Yeah, those can be weird sometimes.
php has had a full object model since v5 (2004)
http://uk3.php.net/manual/en/oop5.intro.php
Gemini BASIC - A very simple calculator BASIC language for a GUI that I wrote for a Dev Engine
Cardinal BASIC - A more advanced BASIC language for Gemini's replacement
Inspiration Script - A scripting language for a game engine that I never released :(
Mini MIPS - For a class in college, based on MIPS Assembly
LiveScript - Scripting language for my company's engines, I also now use it for personal project
It's still very primitive when compared to java or C++.
But you can use php as a scripting language on your computer, though, like python or perl or whatever. It's actually surprisingly suited for it.
Why so many BASIC languages? And why did you have to invent your own language each time? For some of the projects, like the game engine, wouldn't it be better to just implement LUA or something?
Not really, the DOM is object based :?
Because the first two were a long time ago when I didn't have understanding of how compilers worked.
And LiveScript is designed for graphic designers to understand, so it has to be simple and not be too "programming languagy," which python and perl are.
Does all this shit become more clear when taught by someone in university?
I fucking hope so... or else I applied to the wrong dam course.
It depends on the teacher. Some of the teachers learned C++ 15 years ago and never bothered learning the new stuff.
And yes, when you're immersed in it, it will make much more sense. C++ is a weird language compared to some of the other ones.
Oh cool. I certainly hope it will make more sense (if I get accepted), the course looks extremely good. (Includes other things too)
The more advanced a programming language is, the easy it is to program with it. Basically, the makers of the program already did a lot of the work for you.
However advanced programs with a lot of prebuilt commands in it, has more data that has to be read. If your not actually using all the prebuilt commands and stuff, there is wasted code, and thus the final program will run slower than if the commands weren't there.
The reason there are so many languages, is because people have difference needs. Normally its based around time. Either the time it takes to code, or how fast it will run.
If you were making a basic calculator, then speed probably isn't an issue. You would use a language with all the math commands built in already, because its silly to reinvent that code. In this case, your personal time is more valuable.
If however, you are making a really advanced game, or doing the kind of math that involves solving for pi out to a billion numbers, then you want the program to run as fast as possible.
Not true. -s strips unused code, so unused parts of libraries are pulled out.
Some of it is, but not all of it. Here's why. Libraries can be loaded dynamically, meaning outside programs and libraries might use functions within it, even if nothing does internally. These can't be stripped out.
One thing I was wondering. How would you get it to detect a word, or character within a user input?
Like, I know there is this:
But that means the user has to input "fuck" only, and nothing else.Code:if (userinput == "fuck");
cout << "omg you swore, you basterd" << endl;
The way I want it would be more like if the person wrote a whole sentence that included the word "fuck", then it would say "omg you swore..."
Just as an example, of course.
Code:std::string user_input;
std::cin >> user_input;
found_fuck = user_input.find("fuck");
if (found_fuck != std::string::npos)
{
std::cout << "omg you swore, you basterd" << std::endl;
}
Firstly what you're trying there won't work. If you want to compare two strings you need to use strcmp() or something. strcmp() is a function that returns the number of characters that are different between two strings. In your example, you could have written
if (!strcmp(userinput, "fuck"))
(don't forget to include string.h/cstring
and it would have worked as you expected.
But in order to search a string containing more than one word, you'd probably have to loop through it and isolate the words (looking for characters that are not letters), and then compare each word against the word you want to detect.
edit: ... Or you can use the built inn find function of the string class, it seems :p
Absolutely not.
strcmp is for char strings, it's C, not C++. The std::string class has == operators for both other strings and char strings.Code:using namespace std;
string in;
cin >> in;
if (in == "fuck"){
cout << "in == fuck" << endl;
} else if (in.find("fuck") != string::npos){
cout << "in contains fuck" << endl;
}
Slash,
rather than asking little questions here
you may be better off looking stuff up in a reference guide
(it'll be quicker, and you'll learn more)
Eg.
Here's the reference for the string class
http://www.cplusplus.com/reference/string/string/
The methods are at the end
Thanks, guys.
And Ynot, I never noticed that on the site, that will be very handy. Thanks.
lol, no don't do that. If I correct you then you learn more :)
Well. I would like to know how Guitarboy is coming along.
So, Guitarboy? Still at it?
Err, not very good at it.
Trying, but failing.
Aww, oh noes :( What are you stuck on?
I'm not reall quite sure what I should be doing/learning. I'm going to take classes soon (a month, probably) so I'm going to wait until then.
You know, the first few problems on http://projecteuler.net/ are actually really easy, and perfect for you to practice if you don't really have anything to practice with.