• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Sure. I actually just got quite a bit of it working, the only thing that I can't seem to get to function correctly at the moment is my "Clear" button. I need it to Clear my list box (Coordinate List) as well as the big white pane to the left (which clears fine).


CoordinateList.Clear(); is giving me an error. Is there a different way to clear the ListBox?

CoordinateList.Items.Clear(), no?
 

Linkhero1

Member
I'm struggling so much at the moment to understand the Tower of Hanoi recursion.

I understand the concept that I need to move the disks from the start peg to the destination peg using a "utility" peg. I also understand that a bigger disk cannot go on top of a smaller disk. I just can't mentally or do the recursion by hand.

I can't begin programming this in Java without fully understanding this. Can someone please explain to me in the most simplest terms please? I've Googled for an explanation but I still do not understand this recursion. I don't know why I'm struggling so much to understand this as it's said to be the most simple recursion.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Taking the pseudo code from CMU's Computer Science site:
Code:
FUNCTION MoveTower(disk, source, dest, spare):
IF disk == 0, THEN:
    move disk from source to dest
ELSE:
    MoveTower(disk - 1, source, spare, dest)   // Step 1 
    move disk from source to dest              // Step 2
    MoveTower(disk - 1, spare, dest, source)   // Step 3 
END IF
Assume there are 6 discs labeled from 0-5 with 5 being the largest and 0 being the smallest. Also assume that there are 3 pegs labeled A, B and C. The initial state of the puzzle looks like this:

A: [5][4][3][2][1][0]
B:
C:

Say you call MoveTower(5, A, B, C). When your program reaches this line...
Code:
MoveTower(disk - 1, source, spare, dest)   // Step 1
...what happens is that your program will put the call to MoveTower(5, A, B, C) "on hold", and attempt to do MoveTower(4, A, C, B) first.

In MoveTower(4, A, C, B), it will encounter...
Code:
MoveTower(disk - 1, source, spare, dest)   // Step 1
...again, after which it puts MoveTower(4, A, C, B) on hold while it calls MoveTower(3, A, B, C). Each function keeps calling itself until it hits MoveTower(0, A, C, B), at which point it'll move the disc 0 (the smallest one), from A to C, as per this clause...
Code:
IF disc == 0, THEN:
    move disc from source to dest
...resulting in this state of the puzzle:
A: [5][4][3][2][1]
B:
C: [0]

Now, all the MoveTower(...) calls that have been piling up can start resolving one by one in reverse order. The function that was most recently paused was MoveTower(1, A, B, C), which had reached this line:
Code:
move disk from source to dest
The program will then move disc 1 to B, resulting in:
A: [5][4][3][2]
B: [1]
C: [0]

The next line in the function is...
Code:
MoveTower(disk - 1, spare, dest, source)   // Step 3 above
...which translates to MoveTower(0, C, B, A), because it was called during the call to MoveTower(1, A, B, C). Going back to the first disc, the program will encounter...
Code:
IF disc == 0, THEN:
    move disc from source to dest
...again, resulting in this state.

A: [5][4][3][2]
B: [1][0]
C:

The program has just completed the Tower of Hanoi problem for two discs. The next function on the stack is MoveTower(2, A, C, B), and it will do...
Code:
move disk from source to dest
... leading to:
A: [5][4][3]
B: [1][0]
C: [2]

And so on and so forth. I don't think you really need to understand why this specific algorithm works, or how it was deduced. What's important is being able to understand that a function can call itself and how it can be used to solve certain programming problems, particularly those that can be broken down into small yet similar problems.
 

Linkhero1

Member
I'm sort of stuck now.

I was able to program the Tower of Hanoi but I'm stuck at storing the number of disks.

My output should look like this:

OwACG.png



But I'm not sure how to display the values under A, B and C.

The output I get is the following:

NbFsO.png


Edit:

I was thinking of using an ArrayList to store the disk values but I'm not sure how to do that.

Edit 2:

Never mind I think I'm going to use a stack. I think I would have to create three separate stacks in this case?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Stacks and pop()/push() are your friends.
 

youta

Member
Over the last few weeks I've been coding a simple CMS which is currently just a pretty basic file manager. It doesn't really do much of anything yet, but I thought I'd throw it out there for some real world testing: register a few accounts and feel free to play around (keep in mind that it's just a demo, and may be completely wiped out at any moment). If you're in a black hat mood there's a file which belongs to an account called "gaf", feel free to take a crack at it (I hope it's not too easy!) XSS and CSRF attempts are also welcomed.

I realize this is basically asking for free QA, but I managed to convince my employer to release the code under an open-source license (BSD), and whatever comes out of this might benefit others, including perhaps any kind testers out there. So, without further ado,

https://rhxpnew.math.toronto.edu

(the URL will show a self-signed certificate, we're cheap that way).
 

Lkr

Member
i could use a bit of a pointer(har har)
so i have an array of structs and a for loop to enter data to it. i assume the data gets in there. when i send it to a function however to print the data, it doesn't work. i have:

Code:
struct Aa{
int A
int B
char C
};

int main()
{
   Aa mystruct[12];
   for(int x=0;x<12;x++)
   {
      cin >> mystruct[i].A;
   }
return 0;

}

is that successfully holding the data in a loop?
 

Bollocks

Member
i could use a bit of a pointer(har har)
so i have an array of structs and a for loop to enter data to it. i assume the data gets in there. when i send it to a function however to print the data, it doesn't work. i have:

Code:
struct Aa{
int A
int B
char C
};

int main()
{
   Aa mystruct[12];
   for([B]int x=0[/B];x<12;x++)
   {
      cin >> mystruct[[B]i[/B]].A;
   }
return 0;

}

is that successfully holding the data in a loop?

You mixed up the variables, use cin >> mystruct[x].A;
 

Lkr

Member
You mixed up the variables, use cin >> mystruct[x].A;

that was just a translation problem to the internet. i used i in my actual program. that isn't the problem, i wish it had been that simple :(

ax9gBFgvYm.png


this is what my output looks like. fwiw the first value should be a name, second should be a single digit integer, and the third should be a single digit integer :jnc
 

Bollocks

Member
that was just a translation problem to the internet. i used i in my actual program. that isn't the problem, i wish it had been that simple :(

ax9gBFgvYm.png


this is what my output looks like. fwiw the first value should be a name, second should be a single digit integer, and the third should be a single digit integer :jnc

Ah ok, well if you want to read in a string than your current struct layout is wrong.
I assume you want to use char C for that which will not work since this is a single byte so you need to make it an array char C[21] for example to read in a 20 character long string(Always make room for the ending null byte).

Also you can't read in strings with cin if you string contains whitespaces, it will stop reading at a whitespace.
So to read in a string with a char array use char mystr[32]; gets(mystr); Then you can read in whole sentences. If you only want 1 word than as said cin>>mystr works as well.

But I don't know why your numbers are screwed, anyway here's my code that works:
#include <cstdlib>
#include <iostream>
#include <stdio.h>

using namespace std;

struct Aa
{
int A;
int B;
char C[32];
};

int main(int argc, char *argv[])
{
Aa mystruct[3];

//read in
for(int i=0; i<3; i++)
{
cout<<i+1<<". struct\n";
cout<<"Enter a number: ";
cin>>mystruct.A;
cout<<"Enter a second number: ";
cin>>mystruct.B;
fflush(stdin);
cout<<"Enter a string: ";
fgets(mystruct.C, 31, stdin);
//gets(mystruct.C); works as well but unsafe
cout<<"\n";
}

//output
for(int i=0; i<3; i++)
{
cout<<"\n\n"<<i+1<<". struct information";
cout<<"\nA: "<<mystruct.A;
cout<<"\nB: "<<mystruct.B;
cout<<"\nC: "<<mystruct.C;
}

system("pause");
return 0;
}

fflush(stdin); is to clear the input stream, because sometimes there are leftovers and you don't want that, in fact if you comment it, you wouldn't be able to input your string.
 

Lkr

Member
Ah ok, well if you want to read in a string than your current struct layout is wrong.
I assume you want to use char C for that which will not work since this is a single byte so you need to make it an array char C[21] for example to read in a 20 character long string(Always make room for the ending null byte).

Also you can't read in strings with cin if you string contains whitespaces, it will stop reading at a whitespace.
So to read in a string with a char array use char mystr[32]; gets(mystr); Then you can read in whole sentences. If you only want 1 word than as said cin>>mystr works as well.

But I don't know why your numbers are screwed, anyway here's my code that works:

fflush(stdin); is to clear the input stream, because sometimes there are leftovers and you don't want that, in fact if you comment it, you wouldn't be able to input your string.

i already have char names[SIZE] when size is a global const integer at 50 :(
edit::

okay i think i found my problem with the numbers. I am trying to pass the struct to a function. so my function is:

void printsummary(struct name[THESIZE]
and i pass it with printsummary(&thename[NUMPLAYERS]);

am i doing it wrong and it is giving me memory addresses instead of values? when i do an output without a function, it works just fine except the names, which I probably need to fix since I am doing get wrong. if someone can show me how to properly pass the function, i would appreciate it. unfortunately it needs to be a function for this project. when i get rid of the &, it says there is no suitable conversion from struct to struct*

second edit:
fwiw, here is how i am trying to input to my string:
Code:
cin.getline(struct[i].names, SIZE);
where i is the counter i am using for my for loop, names is the char[SIZE]. and SIZE is obv size
 
If I wanted to go about learning how to program in C++ where would people suggest I start? I'm not learning for any reason in particular I just kind of want to know how. If its avoidable I'd rather not buy a textbook, but if there is a really great one I could be convinced. I've never really done anything like this before outside of some basic HTML stuff in the early 2000s.
 

Slavik81

Member
If I wanted to go about learning how to program in C++ where would people suggest I start? I'm not learning for any reason in particular I just kind of want to know how. If its avoidable I'd rather not buy a textbook, but if there is a really great one I could be convinced. I've never really done anything like this before outside of some basic HTML stuff in the early 2000s.

I honestly would recommend starting with a different programming language. Learn to program. Then learn C++. Don't do both at once.
 

Bollocks

Member
i already have char names[SIZE] when size is a global const integer at 50 :(
edit::

okay i think i found my problem with the numbers. I am trying to pass the struct to a function. so my function is:

void printsummary(struct name[THESIZE]
and i pass it with printsummary(&thename[NUMPLAYERS]);

am i doing it wrong and it is giving me memory addresses instead of values? when i do an output without a function, it works just fine except the names, which I probably need to fix since I am doing get wrong. if someone can show me how to properly pass the function, i would appreciate it. unfortunately it needs to be a function for this project. when i get rid of the &, it says there is no suitable conversion from struct to struct*

second edit:
fwiw, here is how i am trying to input to my string:
Code:
cin.getline(struct[i].names, SIZE);
where i is the counter i am using for my for loop, names is the char[SIZE]. and SIZE is obv size

ah ok, if you want to make persistent chances to a passed variable in a subroutine(e.g. after it returns to the main function) you need to pass the variable by reference.
There are 2 methods in C how you can pass a variable to a function:
Call by value
Call by reference
The latter makes persistent changes and is the one you need.

You wrote:
void printsummary(struct name[THESIZE]
which makes it call by value and thus any chances to your code is only valid as long as the program stays in that function.
Also the proper way to do it would be:
void printsummary(struct name)
, there's no need to indicate the size, what if you want to call that function with 32 items, do you write a new function? Function prototypes just need the type.

Also:
printsummary(&thename[NUMPLAYERS])
is wrong. Let's just say NUMPLAYERS is 12. What you did here was pass the address of the 13th element of thename which is none existant because you only allocated 12 so you actually write to random memory.
If you call a function you need to pass the starting adress, &thename which equals to &thename[0].
This also explains why your numbers are all screwed up, first you passed it as value so your changes aren't persistent and second you write to memory space where you don't want too.
So what you're seeing when you print the struct is garbage leftover from a previous program who used that memory space.

So to make persistent changes you need to change your function prototype to:
void printsummary(struct *name);
and call the function with:
printsummary(&thename);
Since this is now a pointer your access modifier changed, it's no longer mystruct.variable but mystruct->variable.
Also if you would do something like mystruct->variable = 12; mystruct->variable would now point to memory adress 12 as I said it's now a pointer.
If you want the value and not the adress just use the * operator: *mystruct->variable, it's called dereferencing.

Welcome to the wonders of C ;)
 

siddhu33

Member
Hello everyone,

I have a question. If i was to develop native iOS applications, do I need to get a Mac and download xCode, or is there a good way that I can develop these said applications on Windows.
 

poweld

Member
Hello everyone,

I have a question. If i was to develop native iOS applications, do I need to get a Mac and download xCode, or is there a good way that I can develop these said applications on Windows.

You need a Mac + XCode, unfortunately.
 
If I wanted to go about learning how to program in C++ where would people suggest I start? I'm not learning for any reason in particular I just kind of want to know how. If its avoidable I'd rather not buy a textbook, but if there is a really great one I could be convinced. I've never really done anything like this before outside of some basic HTML stuff in the early 2000s.

I've read about 3 "beginner" C++ books during my career, and the best, hands down, has to be Accelerated C++. I've heard a lot of praise for C++ Primer (Not the Plus version). You can try to learn through online tutorials, but C++ is the only language complicated enough that you should really get a time-tested book to learn from.
 
I honestly would recommend starting with a different programming language. Learn to program. Then learn C++. Don't do both at once.
What language do you suggest then? I just picked C++ because that's the one that I see most commonly used.

I've read about 3 "beginner" C++ books during my career, and the best, hands down, has to be Accelerated C++. I've heard a lot of praise for C++ Primer (Not the Plus version). You can try to learn through online tutorials, but C++ is the only language complicated enough that you should really get a time-tested book to learn from.

I'll look around town and see if I can find copies maybe if there is one I like enough I'll pick it up.
 

8byte

Banned
Can anyone point me toward some good free C# resources? I'm taking a course right now, and it is god awful. Essentially I have a bunch of poorly written power point slides, and some daft instructions that don't make any sense to me.

So...help? :)
 
Can anyone point me toward some good free C# resources? I'm taking a course right now, and it is god awful. Essentially I have a bunch of poorly written power point slides, and some daft instructions that don't make any sense to me.

So...help? :)

You get what you pay for, and I don't have any free suggestions anyway. I have found the Head First series to be pretty good, and those books aren't overly expensive when you order online. I can't vouch for Head First C# specifically, but the series hasn't generally let me down.

http://amzn.com/1449380344

Beyond that, practice practice practice. And sooner rather than later, get a firm grip on object oriented design. Books on OO and design patterns can help you get there. Not that you want to be a slave to a design pattern or applying patterns where they aren't really appropriate, but they will help you think at a more abstract level.
 
You get what you pay for, and I don't have any free suggestions anyway. I have found the Head First series to be pretty good, and those books aren't overly expensive when you order online. I can't vouch for Head First C# specifically, but the series hasn't generally let me down.

http://amzn.com/1449380344

Beyond that, practice practice practice. And sooner rather than later, get a firm grip on object oriented design. Books on OO and design patterns can help you get there. Not that you want to be a slave to a design pattern or applying patterns where they aren't really appropriate, but they will help you think at a more abstract level.

Jep made the same mistake when learning about design patterns.
Hell the fucking book even warned me about those mistake but i still made them.

I wanted to fit the problem into a design pattern. Such a hassle while when i was just working without the patterns i had it fixed almost instant.

/Make mistake and learn from them..
 

8byte

Banned
You get what you pay for, and I don't have any free suggestions anyway. I have found the Head First series to be pretty good, and those books aren't overly expensive when you order online. I can't vouch for Head First C# specifically, but the series hasn't generally let me down.

http://amzn.com/1449380344

Beyond that, practice practice practice. And sooner rather than later, get a firm grip on object oriented design. Books on OO and design patterns can help you get there. Not that you want to be a slave to a design pattern or applying patterns where they aren't really appropriate, but they will help you think at a more abstract level.

Thanks so much! Looking into these books :)
 
I wanted to fit the problem into a design pattern. Such a hassle while when i was just working without the patterns i had it fixed almost instant.

/Make mistake and learn from them..


Correct. Patterns are best when they emerge in your code almost by accident. What reading about them will do, beyond introducing you to them (obviously), is assist you in recognizing when that pattern is emerging, giving you the experience you need to follow it through. But if you just go in and try to force it, you are probably doing it wrong.

Unfortunately, the common slam is that some programmer reads a pattern book, ignores everything but Singleton, and then uses it everywhere. And then everybody else hates him.
 
Correct. Patterns are best when they emerge in your code almost by accident. What reading about them will do, beyond introducing you to them (obviously), is assist you in recognizing when that pattern is emerging, giving you the experience you need to follow it through. But if you just go in and try to force it, you are probably doing it wrong.

Unfortunately, the common slam is that some programmer reads a pattern book, ignores everything but Singleton, and then uses it everywhere. And then everybody else hates him.

Dat singleton hate.
Some projects groups in the same periode i was learning about design patters were also reading about them and used a shitload of singletons hell their whole android app was made up of singletons. And they wondered why it was so buggy and had so many null pointers.

So far the internet learned me use the singleton only for error logging uses.
 

Apdiddy

Member
I have a question: I have no previous programming/development experience but having been around computers all of my life, I don't feel it would be something that I couldn't pick up and grasp. I know I won't be able to write my programs, but it'll be a start.

Where I work at currently has an opening for a developer on LAMP stack (Linux, Apache, MySQL & PHP). For an absolute newbie in this case, what would be a good starting point or good programs to test/use? Also, if they exist, what are decent training programs to be more proficient with programming?

Thanks for your help NeoGAF code warriors -- go easy on me!

EDIT: Looking at the first page of the thread, I see some GREAT resources that will help.
 
I have a question: I have no previous programming/development experience but having been around computers all of my life, I don't feel it would be something that I couldn't pick up and grasp. I know I won't be able to write my programs, but it'll be a start.

Where I work at currently has an opening for a developer on LAMP stack (Linux, Apache, MySQL & PHP). For an absolute newbie in this case, what would be a good starting point or good programs to test/use? Also, if they exist, what are decent training programs to be more proficient with programming?

Thanks for your help NeoGAF code warriors -- go easy on me!

EDIT: Looking at the first page of the thread, I see some GREAT resources that will help.

A lot of people seem to recommend Python to beginners, and after playing around with the language for a while, I can now completely understand why. Check Udacity CS101. It is by far the best introduction available online to not only programming, but to Computer Science as well. Complete that, and then jump to a PHP book if you are interested in getting that position at your job.

Above all, expect the process to learn programming to take some time. Even if you are truly motivated, and able to devote a significant amount of time, it will still take you months to become proficient. Good luck.
 

Fantastical

Death Prophet
n00b question: I just started a new class and the lab instructions said to print something to stdout. In my last class (an intro class) we just used cout. Is that the same thing? I tried Googling but I couldn't really understand.
 

Lkr

Member
n00b question: I just started a new class and the lab instructions said to print something to stdout. In my last class (an intro class) we just used cout. Is that the same thing? I tried Googling but I couldn't really understand.

standard output is cout i believe

strange issue: my program compiles and runs fine in visual, but when I compile it with g++(which it has to compile with for the course), it gives me a bunch of errors saying missing terminating " character. does anyone know what that means?
 

wolfmat

Confirmed Asshole
cout precisely represents stdout as an object.
strange issue: my program compiles and runs fine in visual, but when I compile it with g++(which it has to compile with for the course), it gives me a bunch of errors saying missing terminating " character. does anyone know what that means?

No idea without the source, but it sounds like you started a string with a ", but forgot the terminating " somewhere. Not sure why visual studio wouldn't complain about this; maybe you're not actually compiling that source and starting it, but using cached compilates? It should really complain.
 

Lkr

Member
cout precisely represents stdout as an object.


No idea without the source, but it sounds like you started a string with a ", but forgot the terminating " somewhere. Not sure why visual studio wouldn't complain about this; maybe you're not actually compiling that source and starting it, but using cached compilates? It should really complain.

i was copying and pasting the source code from my visual file to a nano file on the unix servers we have, and that was causing the problem. i just uploaded the .cpp file itself and it compiled and ran without a hitch, so i'm good now on that regard. next problem:

i don't understand setw. my string is set to allow input of up to 50 characters, but so theoretically i can put setw to 50 for the output of a name, but isn't 50 the max per line? i don't remember how it was explained last semester. all i know is that my values aren't lining up nicely in a table-like fashion, and it is pissing me off lol
 

wolfmat

Confirmed Asshole
i don't understand setw. my string is set to allow input of up to 50 characters, but so theoretically i can put setw to 50 for the output of a name, but isn't 50 the max per line? i don't remember how it was explained last semester. all i know is that my values aren't lining up nicely in a table-like fashion, and it is pissing me off lol

setw's argument describes the minimum width of input characters. If your input is less than that on the related stream, then it uses padding with the character set with setfill, with the method set with the adjustfield flag, although I'm not sure what the latter means, but let's assume it pads left by default (which is what you want).

So for example, you do
Code:
cout << setfill (' ') << setw (10);
cout << "bla";
setw (10);
cout << "bla" << endl;
And then you should end up with
Code:
       bla       bla
Something like that.

What probably trips you up is that you have to use setw everytime you want a tab-like padding.

Edit: Of course, this all can take place on one line.
Code:
cout << setfill ('_') << setw (10) << "bla" << setw (10) << "bla" << endl;
 

FerranMG

Member
I have a question I don't know how to approach, hope somebody can help! I'm actually programming in Objective-C, but I guess any approach could help.

The thing is, I'd like to be able to determine if a dot collides with an arc of a circumference.
For example, let's say I draw an open circumference like this: C
And say there's a moving dot inside this this circle.
I'd like to know if the dot collides with the walls of the open circumference.

I know I can get a bounding box for the open circumference but, of course, this doesn't give me enough detail.

Any thoughts?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
EDIT: How much information about the circumference do you have?

Assuming it's a circle, you'd need to do two comparisons:

1) Check the distance between the center of the circle and the dot, if it exceeds the radius of the circle, then the dot just left the circle. You can go one step further with a line segment-circle collision test, which I can't remember off the top of my head.
2) Bring the dot into the circle's local space and rotate the system so that the x axis bisects the open side of the circle. Then calculate the angle between the circle's center to the dot, and the x axis, assuming the origin is the circle's center. If it's within some angle, then it did not hit the walls of the circle.
 

Fantastical

Death Prophet
Another n00b question. I need to read contents from a file into stdin.

The command line will look like "./program < example.txt", but I don't understand how to read that text and assign the data to variables. Example.txt contains multiple lines each line containing an age, gender, and distance with decimals. If I was opening from ifstream I would know what to do

while ( input_file >> age >> gender >> distance)

but I don't know how to do it from stdin. Do I have to use getline?

EDIT: I used istringstream and it worked.
 

FerranMG

Member
EDIT: How much information about the circumference do you have?

Assuming it's a circle, you'd need to do two comparisons:

1) Check the distance between the center of the circle and the dot, if it exceeds the radius of the circle, then the dot just left the circle. You can go one step further with a line segment-circle collision test, which I can't remember off the top of my head.
2) Bring the dot into the circle's local space and rotate the system so that the x axis bisects the open side of the circle. Then calculate the angle between the circle's center to the dot, and the x axis, assuming the origin is the circle's center. If it's within some angle, then it did not hit the walls of the circle.

Actually, what I'd like is to be able to make the dot "bounce back" if it collides with the circumference.
What you propose would be cool to see if the dot is inside or outside the circumference, though I liked a lot the second solution!

I google "line segment - circle collision" and I got something I think that will help.
Basically consisting on getting the line the dot is following, and see if it intersects with the circumference.
For reference.

I thought maybe there would be an already implemented method for that, or maybe a way to get an object such as a bonding circumference for my circumference. I see I'm gonna have to implement it myself. :p

Thanks a ton for you help!
 
i could use a bit of a pointer(har har)
so i have an array of structs and a for loop to enter data to it. i assume the data gets in there. when i send it to a function however to print the data, it doesn't work. i have:

Code:
struct Aa{
int A
int B
char C
};

int main()
{
   Aa mystruct[12];
   for(int x=0;x<12;x++)
   {
      cin >> mystruct[i].A;
   }
return 0;

}

is that successfully holding the data in a loop?
You've got i as your index var inside the loop but you're actually using x. This shouldn't even compile cause i isn't declared anywhere.

Edit: okay, we'll others handled it already. My bad.
 
Top Bottom