• 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.

C++ Help?

Status
Not open for further replies.

deadbeef

Member
Zombie Lyle said:
Is a pointer always 4 bytes for an int, char or float?

Also guys, I hate to ask loads of questions but I'm useless at C++. I don't know how to use a vector as an array. The question is below.

Write the C++ code to dynamically create a vector of 100 long integers. Explain how you could use this block of memory as a two dimensional array of 10 by 10 long integers. Also give the code to release the vector.

Well, a pointer is just an address, so a pointer is typically always the same size on a given system, except for things like "far" pointers on some embedded architectures, but don't worry about that.

If a pointer to an int is 4 bytes, so is a pointer to a char. And if a pointer to an int is 8 bytes, then a pointer to a char is as well.
 
Zombie Lyle said:
Hey, I'm looking over past papers for my C++ exam next week and can't find the answer for this question.

In C++ how may bytes of memory are occupied by an array of 150 integers and an array of 150 character pointers.

Thanks in advance.

Depends on the platform architecture.
 

Rapstah

Member
Code:
int main()
{
	string str_line; // Used for holding loaded lines from the file(s).

	// Example of correct format: string str_hugeteststring = "|objectone|objecttwo|objectthree|potato|robot|";
	// Where "str_returnobjectofline(0, str_hugeteststring)" would return "objectone".

	ifstream monsterdatafile ("monsterdata.mda"); // This file is in the executable's directory.

	if (monsterdatafile.is_open())
	{
		while (monsterdatafile.good())
		{
			getline (monsterdatafile, str_line);  // Load the first line (?)

			monsters[1].name = str_returnobjectofline(0, str_line);					// Save its first portion (between first and second bracket) in name var.
			monsters[1].level = GetIntVal(str_returnobjectofline(1, str_line));		// second portion, level var.
			monsters[1].maxHP = GetIntVal(str_returnobjectofline(2, str_line));		// etc.
			[B]monsters[1].alignment = str_returnobjectofline(3, str_line);[/B]
		}
		monsterdatafile.close();
	}
	

	// STRUCTS INCOMING
	cout << monsters[1].name << " " << monsters[1].level << " " << monsters[1].maxHP << " " << monsters[1].alignment << endl;
	
	_getch();		// Placeholder thing to pause application at end.

	return 0;
}

This is my current main() function that I'm having problems with. What this does is it opens a text file and loads data for some random RPG-sounding NPC-style structs. There are a couple of functions defined outside of it but I know throug extensive testing (and verbose debugging) that they do exactly what they should.

The issue I'm running into is that it's running str_returnobjectofline(int, str) a fifth time after the last intentional time it's run (noted in bold). This results in this last portion getting only a start point and no end point, meaning the string it tries to create goes negative in length and the application crashes.

I know that getline tries to read the remaining two lines in the file (see below) as well, but since I'm not actually trying to put those anywhere, is that ruining the program? Ask if there's anything unclear about how this runs, I think I understand it all myself.

Here's monsterdata.mda for reference: the file extension is obviously just for show.
Peasant|4|35|Neutral lawful|
Snake|1|10|Animal|
Dragon|65|1800|Evil lawful|
Why does it continue loading data from the first string when I'm not asking for it?
 

CrankyJay

Banned
Need more info. Where is your definition of monsters[]? Can you show the exact output you're getting?

Also, have you tried removing the other two lines to see if that fixes the crash? Make sure there is no carriage return at the end of the first line, otherwise the program will recognize it as a second line.
 

wolfmat

Confirmed Asshole
Put the getline into the condition and check its return value before you do the body of the while. You should only do str_returnobjectofline under the condition that the getline yielded something you can actually use.

Edit: While you're at it, check whether the getline resulted in an empty string.
 

gblues

Banned
wolfmat said:
Put the getline into the condition and check its return value before you do the body of the while. You should only do str_returnobjectofline under the condition that the getline yielded something you can actually use.

Edit: While you're at it, check whether the getline resulted in an empty string.

This. You're not doing any error checking on your call to getline(). If you have a blank line at the end of your data file, the last "real" line of the file won't set the EOF flag, which means good() will return true and your code tries to read the blank line.
 
Hey I'm writing a dialog-based C++ MFC encryption program. I can't get it to work and I'm really stuck.
Code:
srand((unsigned)time(NULL));
	int seed = rand();
	int key = (int)ran2(seed);
	int stringLength = str_input.GetLength();
	
	for(int i = 0; i < stringLength; i++)
	{
		cipherText = str_input.GetAt(i) ^ key;
		str_input.AppendChar(c);
	}

	encipherBox.SetWindowText(str_input);

Instead of encrypting anything it just prints out the string I entered into a text box twice.
 

fenners

Member
Zombie Lyle said:
Hey I'm writing a dialog-based C++ MFC encryption program. I can't get it to work and I'm really stuck.
Code:
srand((unsigned)time(NULL));
	int seed = rand();
	int key = (int)ran2(seed);
	int stringLength = str_input.GetLength();
	
	for(int i = 0; i < stringLength; i++)
	{
		cipherText = str_input.GetAt(i) ^ key;
		str_input.AppendChar(c);
	}

	encipherBox.SetWindowText(str_input);

Instead of encrypting anything it just prints out the string I entered into a text box twice.

What are you doing with cipherText?
 

poweld

Member
CrankyJay said:
What are you using the ^ operator for?
XOR is often used for symmetric key encryption. If you use XOR with a key and a piece of data, and then XOR that product with the key again, you will end up with the original data.
 

Nesotenso

Member
Hi I need some help from you guys. I have a beginners level knowledge of C++. I am looking to improve my C++ over a year and would like to learn to C as well as it is used a lot with assembly in micro-controllers.

1) So any suggestions regarding online resources and books so I could substantially expand on my knowledge and improve my C/C++ skills?

2) I am a graduate student , I intend to emphasize in IC design( ASIC, RFIC's ,analog and mixed signal system design) and even work with digital systems. So I was thinking of learning x86 assembly. Is anyone else on gaf aware of good resources to learn x86 assembly and free assemblers ? Is it beneficial along with Verilog if you are looking to work in digital design?
 

poweld

Member
vordhosbn said:
Can anyone show me an example of how to use arrays and a for and do loop?
Code:
int main(int argc, char** argv) {
    const uint32_t arraySize = 100;
    uint32_t someNums[] = (uint32*)malloc(sizeof(uint32_t)*arraySize));
    if (someNums == NULL) {
        return -1;
    }

    uint32_t i;

    for (i = 0; i < arraySize; ++i) {
        someNums[i] = i;
    }

    i = 0;
    do {
        printf("someNums[i] = %d\n", someNums[i]);
        ++i;
    } while(i < arraySize);
    
    if (someNums != NULL) {
        free(someNums);
    }

    return 0;
}
edit: made more proper
 

BosSin

Member
Just a quick question, I am a java guy doing some c++ for uni work and being a java guy I saw this:
Code:
#define times(a,b) a*b
// some code
cout<<"a*b is "<<times(1+2, 2+3)<<endl;
and naturally thought 15.
Turns out that when I ran it through visual studio the returned value is 8. Is this because it effectively does: (1*2) + (2*3) = 8

EDIT: is this because it calls times twice like: times(1+2, 2+3) (bolded being what it is called on) then times(1+2, 2+3)

Does this depend on the compiler you are using, or is it universal? Is this the kind of output you would get from gcc?
 

poweld

Member
BosSin said:
Just a quick question, I am a java guy doing some c++ for uni work and being a java guy I saw this:
Code:
#define times(a,b) a*b
// some code
cout<<"a*b is "<<times(1+2, 2+3)<<endl;
and naturally thought 15.
Turns out that when I ran it through visual studio the returned value is 8. Is this because it effectively does: (1*2) + (2*3) = 8

EDIT: is this because it calls times twice like: times(1+2, 2+3) (bolded being what it is called on) then times(1+2, 2+3)

Does this depend on the compiler you are using, or is it universal? Is this the kind of output you would get from gcc?
times(1+2, 2+3) becomes 1+2*2+3. All macros do is dumb substitution, and this is universal. As you can see, by order of operations, 2*2 = 4, + 1 + 3 = 8

If you wanted this macro to work as expected, wrap a and b with parentheses.

#define times(a,b) (a)*(b)
 
BosSin said:
Just a quick question, I am a java guy doing some c++ for uni work and being a java guy I saw this:
Code:
#define times(a,b) a*b
// some code
cout<<"a*b is "<<times(1+2, 2+3)<<endl;
and naturally thought 15.
Turns out that when I ran it through visual studio the returned value is 8. Is this because it effectively does: (1*2) + (2*3) = 8

EDIT: is this because it calls times twice like: times(1+2, 2+3) (bolded being what it is called on) then times(1+2, 2+3)

Does this depend on the compiler you are using, or is it universal? Is this the kind of output you would get from gcc?

I'm not certain, but it might be doing this:
times(1+2, 2+3)
bcomes
1+2 * 2+3

This would be 8.


Beaten. That's what I get for trying to paste the code in a text file and compile it first. :p
 

BosSin

Member
Ah I see ...
oh and by the way this is from an exam question, it just kinda stumped me because I thought "whaaaaa... 8? how can this be!!!"

(Also it didn't help that the main focus of the subject was image processing and c++ was just glanced over)
 

BosSin

Member
I know I've already asked a question, but the material they give sucks and the exam paper is purposefully made in order to trick people who are attempting it.

So, say I have:
Code:
char *s = "ABCD";
*s++;
cout << "s is " << s << endl
For this I thought the answer would be BBCD because incrementing *s should result in an increment to the first item in the list, and A+1 = B. Outputting s would result in each item being printed right?

however, running it through visual studio gave me "BCD" as output, but I thought this would only happen when we change the actual location a pointer is referring to (so this should only happen with s++)
 

poweld

Member
BosSin said:
I know I've already asked a question, but the material they give sucks and the exam paper is purposefully made in order to trick people who are attempting it.

So, say I have:
Code:
char *s = "ABCD";
*s++;
cout << "s is " << s << endl
For this I thought the answer would be BBCD because incrementing *s should result in an increment to the first item in the list, and A+1 = B. Outputting s would result in each item being printed right?

however, running it through visual studio gave me "BCD" as output, but I thought this would only happen when we change the actual location a pointer is referring to (so this should only happen with s++)
++ and -- operators have priority over the * operator

This means that the ++ takes place before the *, so you are incrementing the pointer position by one, so that it now points to the 'B'. When you dereference the pointer and display it as a string (until the null terminator) you will see "BCD"

See the end of this page: http://www.cplusplus.com/doc/tutorial/operators/

edit: To make this work the way you're expecting it to, you'd want to instead do
Code:
(*s)++;
 

BosSin

Member
thanks guys, I've never required such careful consideration about this kinda stuff as most of the programming I would usually do is on a higher level (and this is with like 4-5 years experience)
 

DrStiles

Member
BosSin said:
I know I've already asked a question, but the material they give sucks and the exam paper is purposefully made in order to trick people who are attempting it.

So, say I have:
Code:
char *s = "ABCD";
*s++;
cout << "s is " << s << endl
For this I thought the answer would be BBCD because incrementing *s should result in an increment to the first item in the list, and A+1 = B. Outputting s would result in each item being printed right?

however, running it through visual studio gave me "BCD" as output, but I thought this would only happen when we change the actual location a pointer is referring to (so this should only happen with s++)

I may be a little rusty on this, since I haven't used c++ in a while .*s is the location where the string is being stored. So you actually are changing the location when you increment the pointer to be one char further, making the output be "BCD".
 

Atruvius

Member
I asked this in the stupid questions thread, but I think this fits here better.

I want to learn C++, but I know nothing of it. What would be the quickest/easiest way to start learning? Any sites you guys know?

What programs should I have on my PC? I just downloaded Microsoft Visual C++ 2010 Express Setup, is there any other programs I should have?

Thanks.
 

CrankyJay

Banned
Atruvius said:
I asked this in the stupid questions thread, but I think this fits here better.

I want to learn C++, but I know nothing of it. What would be the quickest/easiest way to start learning? Any sites you guys know?

What programs should I have on my PC? I just downloaded Microsoft Visual C++ 2010 Express Setup, is there any other programs I should have?

Thanks.

You can try Eclipse as well for an IDE.

As for sites, just google C++ beginners tutorials.
 
Atruvius said:
I asked this in the stupid questions thread, but I think this fits here better.

I want to learn C++, but I know nothing of it. What would be the quickest/easiest way to start learning? Any sites you guys know?

What programs should I have on my PC? I just downloaded Microsoft Visual C++ 2010 Express Setup, is there any other programs I should have?

Thanks.


Hah, I was moments from clicking Submit on a suggestion that you bring your questions to this thread. :)


Where are you starting from? Do you know any other languages? If so, which languages do you already know (if you've done BASIC or PASCAL, then there's a lot of syntax learning for you to do -- if you've played with Perl or Java, then it'd be a much easier jump)? Have you programmed in compiled languages? Do you know object oriented programming yet? Do you prefer text-based programming or the kind where you drag widgets around?

I'm incredibly partial to the Qt libraries, because they turn C++ from "fuck damn you work!" to "leaving early for vacation because everything's done". But if you went the route I took, there's a lot in stock C++ that you'll simply end up not learning (like the entire strings library, which I started looking into only recently), and if you're looking to work in a team then it's probably much better to learn just the regular language, because then you'll be on the same level as everyone else. But I'm still putting it out there because of massive &#9829;&#9829;&#9829;.

The cplusplus.com reference site has been helpful for me in the past, and oddly I tend to learn a lot about individual common functions on Wikipedia.

Googling tutorials, as CrankyJay suggested, is of course a great idea. I suggest hunting down the ones written on .edu domains, as they're specifically with education in mind.

This thread, of course, is probably pretty good for helping, too. &#9786;


( Edit: Note about my suggestion regarding searching .edu domains for tutorials: They generally teach on unix-like systems. That means (assuming that your PC does not have a unix-style compiler installed on it, which is fine) that you'll have to work out how to do the actual compiling part elsewhere, but beyond that the basics of the language are the same. And I still stand by my suspicion that the language breakdown is better on university sites )
 

Atruvius

Member
I am a complete noob. I know absolute zero about coding and languages. There'll be no school for a few months, so I have lots of time to learn.

And I'm now downloading Eclipse 3.2. I also downloaded The Eclipse IDE for C/C++ Developers but some error came and I couldn't open it.
 
Atruvius said:
I am a complete noob. I know absolute zero about coding and languages. There'll be no school for a few months, so I have lots of time to learn.

And I'm now downloading Eclipse 3.2. I also downloaded The Eclipse IDE for C/C++ Developers but some error came and I couldn't open it.

Eclipse is just going to make you want to kill yourself. Use Visual C++ Express Edition
 

maharg

idspispopd
Or if you're on the non-windows end of things (OSX/Linux), give QtCreator a go. It's the closest to VStudio experience I've had on other platforms. Reminds me a lot of pre-bloat VC++, though it's got its share of bloat as well.
 

wolfmat

Confirmed Asshole
If you've never ever touched a programming language, then you want to go through the manual way of compiling, at least for your first hello.cpp up until maybe your first toh.cpp. So fuck IDEs. Write code in some text editor. Compile stuff with some compiler like gcc from the command line.

Once you're comfortable with the manual way, move on to IDE magic.

IDEs exist to make the complex projects more bearable. They're not for beginners at all.
 

Konig94

Neo Member
Alright, so I'm trying to write a program that will take one text file full of all possible three-letter combinations (out.txt) and compare each one to a dictionary text file to see if the three letters appear in each word in the order they're in. For example one of the things that it will check is that the three-letter combination "org" appears in the word "original". Each combination has a count of the number of words it appears in and will be written out to another text file (new.txt).

Now, for some reason the program only checks the first three-letter combo, and when it displays it, it's after every other three-letter combo has been displayed. It's probably just some stupid error like some extra braces or some other stupid shit, but I've been staring at it for a while, and I have no idea what's wrong. Also, for testing purposes I have only included one word in the dictionary file: "aaas" (otherwise there would be 5.3 billion comparisons going on every test). Thanks for any help.

Code:
#include <iostream>
#include <fstream>

using namespace std;

int main () {

    ifstream dictionary;
    ifstream out("out.txt");
    ofstream ofst("new.txt");
    string tempOut = "", tempDictionary = "";
    
    while(!out.eof()) {
        
        getline(out, tempOut);
        cout << tempOut << "\tWhy do I only appear once?";    //all of the tempOut's get printed (all 17576 of them), and then the message after it appears
        cout << "\nAnd why do I only appear once?\n";
        int count = 0;
        dictionary.open("dictionary.txt");
        cout << "!!! " << dictionary.eof() << " !!!";
        while(!dictionary.eof()) {
            
            getline(dictionary, tempDictionary);                
            int one = 0, two = 0, three = 0;
            cout << "\t(" << tempOut.substr(0,1) << " =? " << tempDictionary.substr(one, 1) << ")\t";
            while(tempOut.substr(0, 1) != tempDictionary.substr(one, 1)) {
                
                if(one + 1 != tempDictionary.length()) {
                    
                    ++one;
                }
                else {
                    
                    one = -1;
                    break;
                }
            }
            if(one > -1 && one < tempDictionary.length() - 3) {
                
                cout << "\tOne: " << one << "\t";
                two = one + 1;
                while(tempOut.substr(1, 1) != tempDictionary.substr(two, 1)) {
                    
                    if(two + 1 != tempDictionary.length()) {
                        
                        ++two;
                    }
                    else {
                        
                        two = -1;
                        break;
                    }
                }
            }
            if(two > 0 && two < tempDictionary.length() - 2) {
                
                cout << "\tTwo: " << two << "\t";
                three = two + 1;
                while(tempOut.substr(2, 1) != tempDictionary.substr(three, 1)) {
                    
                    if(three + 1 != tempDictionary.length()) {
                        
                        ++three;
                    }
                    else {
                        three = -1;
                        break;
                    }
                }
            }
            
            if(three > -1) {
                ++count;
            }
            
        }
        dictionary.close();
        cout << ": " << count << endl;
        if(count > 0) {
            
            if(count < 10) {
                
                ofst << "00000" << count << tempOut << endl;
            }
            else if(count < 100) {
                
                ofst << "0000" << count << tempOut << endl;
            }
            else if(count < 1000) {
                
                ofst << "000" << count << tempOut << endl;
            }
            else if(count < 10000) {
                
                ofst << "00" << count << tempOut << endl;
            }
            else if(count < 100000) {
                
                ofst << "0" << count << tempOut << endl;
            }
            else {
                
                ofst << count << tempOut << endl;
            }
        }
        
    }
    ofst.close();
    out.close();
    dictionary.close();
}

Here's a small sample of the output at the end:
Code:
zzp
zzq
zzr
zzs
zzt
zzu
zzv
zzw
zzx
zzy
zzz	Why do I only appear once?
And why do I only appear once?
!!! 0 !!!	(a =? a)		One: 0		Two: 1	: 1
 
D

Deleted member 30609

Unconfirmed Member
Hey guys. Does anyone have an C++ book recommendations for people with previous programming experience (Java, but anything that assumes prior OO experience is fine)?

I'm just looking to get basic syntax and the like down before uni starts up again. I'm looking for things like the basic style and structure of C++ relative to something like Java as opposed to "hey guys, this what a private attribute is", you know? Maybe some general tips on when to pass a reference as opposed to a duplicate, stuff that Java does automatically.

I started programming six months ago, so far I really enjoy it.
 

Wichu

Member
Konig94 said:
Alright, so I'm trying to write a program that will take one text file full of all possible three-letter combinations (out.txt) and compare each one to a dictionary text file to see if the three letters appear in each word in the order they're in. For example one of the things that it will check is that the three-letter combination "org" appears in the word "original". Each combination has a count of the number of words it appears in and will be written out to another text file (new.txt).

Now, for some reason the program only checks the first three-letter combo, and when it displays it, it's after every other three-letter combo has been displayed. It's probably just some stupid error like some extra braces or some other stupid shit, but I've been staring at it for a while, and I have no idea what's wrong. Also, for testing purposes I have only included one word in the dictionary file: "aaas" (otherwise there would be 5.3 billion comparisons going on every test). Thanks for any help.
Looks like getline(out, tempOut) is reading the whole file. What separators are you using in out.txt?
Also, instead of the bit where you check the number of digits in the number and pad accordingly, you can use formatting flags:
Code:
ofst.width(6);
ofst.fill('0');
ofst << count << tempout << endl;
I think that should work. The width flag only affects the next thing sent to the output (i.e. count).
 

Gaspode_T

Member
Rez said:
Hey guys. Does anyone have an C++ book recommendations for people with previous programming experience (Java, but anything that assumes prior OO experience is fine)?

I'm just looking to get basic syntax and the like down before uni starts up again. I'm looking for things like the basic style and structure of C++ relative to something like Java as opposed to "hey guys, this what a private attribute is", you know? Maybe some general tips on when to pass a reference as opposed to a duplicate, stuff that Java does automatically.

I started programming six months ago, so far I really enjoy it.

If you started programming six months ago you don't really have enough exp to claim you have previous prog experience...probably the simpler but beginner books are better, if you really had 10 years of experience or something a reference book might be okay.

C++ Primer Plus was always one of my faves
 
D

Deleted member 30609

Unconfirmed Member
Gaspode_T said:
If you started programming six months ago you don't really have enough exp to claim you have previous prog experience...probably the simpler but beginner books are better, if you really had 10 years of experience or something a reference book might be okay.

C++ Primer Plus was always one of my faves
The problem with a lot of the "Welcome to C++ books" are that large chunks of time are spent repeating material from books I already own, or lectures I've already sat in. I'm just trying to get my money's worth, not flaunt knowledge.

Edit: C++ Primer Plus sounds excellent. It's reasonably priced too, which is nice. Cheers.
 

Konig94

Neo Member
Wichu said:
Looks like getline(out, tempOut) is reading the whole file. What separators are you using in out.txt?
Also, instead of the bit where you check the number of digits in the number and pad accordingly, you can use formatting flags:
Code:
ofst.width(6);
ofst.fill('0');
ofst << count << tempout << endl;
I think that should work. The width flag only affects the next thing sent to the output (i.e. count).

Ahh, thank you. I was using new lines as separators, but apparently copying and pasting between Word, and TextEdit fucked up the formatting. Also, thanks for the formatting tip, didn't know about width or fill.
 

Man

Member
More of a (very basic)math problem than an actual C++ problem.

Usually when you have pong or similar you have a velocity X and Y.
When this moving ball hits a stationary circle you just update the velocity vector in the bounce direction.

Now... I have a missile and this missile has yaw controlling it's direction. This missile bounces around a square room but there will also be circle objects there to bounce off.

When it hits the upper and bottom walls I just reflect it: yaw = -yaw;
I don't bounce of left and right walls.

From the onset the missile is pointed towards World space X+ direction:
World space and traveling in the X+ direction equals yaw 0.
World space and traveling in the X- direction equals yaw 180.

Missile has X and Y. It has a radius.
Similarly the circular object.

How do I calculate the bounce direction and transform this to a degree value I can either +/- towards the missile yaw value? I need the angular displacement.

edit:
Maybe it's: yaw -= (angularDisplacementToPerpendicularOfCircleNormal * 2)
 
Rez said:
Hey guys. Does anyone have an C++ book recommendations for people with previous programming experience (Java, but anything that assumes prior OO experience is fine)?

I'm just looking to get basic syntax and the like down before uni starts up again. I'm looking for things like the basic style and structure of C++ relative to something like Java as opposed to "hey guys, this what a private attribute is", you know? Maybe some general tips on when to pass a reference as opposed to a duplicate, stuff that Java does automatically.

I started programming six months ago, so far I really enjoy it.

I'm reading Accelerated C++. This book condenses a lot of the most useful concepts in the C++ language to get you up and running quickly.

Man said:
More of a (very basic)math problem than an actual C++ problem.

Usually when you have pong or similar you have a velocity X and Y.
When this moving ball hits a stationary circle you just update the velocity vector in the bounce direction.

Now... I have a missile and this missile has yaw controlling it's direction. This missile bounces around a square room but there will also be circle objects there to bounce off.

When it hits the upper and bottom walls I just reflect it: yaw = -yaw;
I don't bounce of left and right walls.

From the onset the missile is pointed towards World space X+ direction:
World space and traveling in the X+ direction equals yaw 0.
World space and traveling in the X- direction equals yaw 180.

Missile has X and Y. It has a radius.
Similarly the circular object.

How do I calculate the bounce direction and transform this to a degree value I can either +/- towards the missile yaw value? I need the angular displacement.

edit:
Maybe it's: yaw -= (angularDisplacementToPerpendicularOfCircleNormal * 2)

arctan(y/x)?
 

Man

Member
Lasthope106 said:
arctan(y/x)?
Yeah right. Still, even when the rocket and circle is perfectly aligned against each other, the rocket bounces to the side. It should bounce straight back where it came from.


//---------------game-----------------
void Game::collideWithCircle(Rocket *rocket, float x, float z)
float dx = x - rocket->X(); //5 - 4 (rocket radius is 0.5, circle radius is 0.5)
float dz = z - rocket->Z(); //always 0
float normal = atan2(-dz, -dx);
float newRocketAngle = reflect(rocket->getYawAsRadian(), normal);
if (newRocketAngle < 0) {
newRocketAngle += 2 * PI;
}
else if (newRocketAngle > 2 * PI) {
newRocketAngle -= 2 * PI;
}
float yawDegree = newRocketAngle * (180 / 3.1415926535f);
rocket->setYaw(yawDegree);
}


float Game::reflect(float angle, float normal) {

angle = 2 * normal - PI - angle;
if (angle == -PI)
angle = 180.0f;

while (angle < 0) {
angle += 2 * PI;
}
while (angle > 2 * PI) {
angle -= 2 * PI;
}
return angle;
}

//----------------rocket---------------
float Rocket::getYawAsRadian() { return m_yaw * (3.1415926535f / 180); }

For some reason this causes it to bounce sideways.
If the check is done shorter than the radius of the circle, does that have anything to say?

edit: posting it here helped. I noticed in the code above this part inside reflect():
if (angle == -PI)
angle = 180.0f;

Something I had entered in earlier frustrations. It seems to be working now.
 

The Technomancer

card-carrying scientician
Okay, so that I stop cluttering up the other thread I'll bump this. What does it mean when I get an error reading "'static' should not be used on member functions defined at file scope" while trying to declare a static method in a class?
 

The Technomancer

card-carrying scientician
Sorry to double post, but I'm really stumped about an issue passing a vector into a function, and even google doesn't seem to help. For some reason trying this:
Code:
void System::Draw(sf::RenderWindow App, std::vector<SolidObject*> Mobile()){
	for(int i = 0; i < (Mobile.size()); i++){
			App.Draw(Mobile[i]->Sprite);
		}
}
produces errors, while extremely similar code in the main function:
Code:
std::vector<SolidBrick *> bricks(6);
	bricks.size();
for(int i = 0; i <6; i++){
			App.Draw(bricks[i]->Sprite);
		}
compiles just fine. Errors are
Code:
error C2228: left of '.size' must have class/struct/union
1>          type is 'std::vector<_Ty> (__cdecl *)(void)'
1>          with
1>          [
1>              _Ty=SolidObject *
1>          ]

subscript requires array or pointer type

left of '->Sprite' must point to class/struct/union/generic type
 

Wichu

Member
Not sure on your first error (you've probably misused the 'static' keyword somewhere).
Passing a vector to a function is possible. Did you define the function in your header file with exactly the same argument types? Also, System is your own class (not sf::System), right?

By the way, you'll want to pass a sf::RenderWindow and a vector by reference rather than by value (as you're doing now). Each time you call the function, it will have to allocate memory and copy the objects you passed in; if the vector gets large, this is really inefficient (not to mention the problems with pointers in the objects you pass in). I think sf::RenderWindow inherits sf::NonCopyable, so I don't think it will compile like this anyway.
Passing by reference means the function will use the original object rather than trying to copy it. To pass by reference, put a & after the argument type:
Code:
void System::Draw(sf::RenderWindow[b]&[/b] App, std::vector<SolidObject>& Mobile) {
    // stuff
}
Also notice I changed it from a vector of pointers to a vector of objects. This is generally more efficient, as you don't need to worry about dereferencing and deleting pointers (ignore this if you're storing the objects somewhere else).

Alternatively, you can pass in &Mobile[0] as a SolidObject*; internally, a std::vector contains an array, so you can treat the pointer to the first element of the vector as an array identifier.

Someone correct me if I'm wrong :p
 

Kalnos

Banned
Wichu said:
Someone correct me if I'm wrong :p

Looks great to me, especially keep in mind what he said about passing by reference. It's crucial for performance and usually it's key for what you're wanting to do.

Also, SFML was a good choice, it's pretty easy to use.
 

The Technomancer

card-carrying scientician
Heh, thanks guys! Did either of you catch my edit though, where the nature of the problem changed drastically? I could use a bit of advice on this problem now.

Glad you pointed out the Reference thing Wichu, that would have seriously screwed up my Renderwindow. And yeah, System is my own custom class.
 

fenners

Member
Wichu said:
Also notice I changed it from a vector of pointers to a vector of objects. This is generally more efficient, as you don't need to worry about dereferencing and deleting pointers (ignore this if you're storing the objects somewhere else).

He's using a Pointer because in the other thread, SolidBrick is a baseclass to a variety of different classes. If he just allocates a vector of SolidBrick, it won't work for what he needs.
 

The Technomancer

card-carrying scientician
fenners said:
He's using a Pointer because in the other thread, SolidBrick is a baseclass to a variety of different classes. If he just allocates a vector of SolidBrick, it won't work for what he needs.
Yup, thanks. Still stymied why its not letting me access a vector method or why it won't let me look at the "Sprite" of one of the objects.
 

mclem

Member
I'd want to fiddle with the code directly to make sure, but my gut's telling me that in:

Code:
void System::Draw(sf::RenderWindow App, std::vector<SolidObject*> Mobile[b]()[/b]){

...you want to drop the bolded brackets (Edit: Which aren't actually very visibly bolded at my end. The bracket pair immediately following "Mobile"). I think it thinks you're passing in a function (which returns a vector?), not the vector itself. Unless you are actually meaning to pass in a function?
 

maharg

idspispopd
mclem said:
I'd want to fiddle with the code directly to make sure, but my gut's telling me that in:

Code:
void System::Draw(sf::RenderWindow App, std::vector<SolidObject*> Mobile[b]()[/b]){

...you want to drop the bolded brackets (Edit: Which aren't actually very visibly bolded at my end. The bracket pair immediately following "Mobile"). I think it thinks you're passing in a function (which returns a vector?), not the vector itself. Unless you are actually meaning to pass in a function?

Yes. Also you should pass it in by const ref. Really not sure why you'd have put those () on there.

*sigh* this is, in full, what you probably really want to be doing here. You're passing things in by value which you really shouldn't, and you should be using the iterators to go through the vector, not indexes.

Code:
void System::Draw(sf::RenderWindow &App, const std::vector<SolidObject*> &Mobile){
	for(std::vector<SolidObject*>::iterator it = Mobile.begin(); it != Mobile.end(); it++){
			App.Draw(it->Sprite);
		}
}

Are you coming from a java or c# background? Because in those languages everything is passed by reference by default (with some exceptions). In C++ everything is passed by value by default.
 

The Technomancer

card-carrying scientician
Actually from a C++ background, but even though I know a fair amount I'm not very confident in it. I think I really fucked that over last night because I kept adding combinations of * and & trying to figure out which combination worked. I had the () because I'm used to passing an array as Array[].
Yeah, I should be passing as a const, and that's something I've added for this function now. In the future though there may be times that I don't since I want to write functions that actually interact with the passed vector: that's how I'm planning on actually doing anything with it.

Trying the code posted above now, current issue is that I'm getting errors saying that
Code:
Error	1	'initializing' : cannot convert from 'std::_Vector_const_iterator<_Myvec>' to 'std::_Vector_iterator<_Myvec>'

Error	2	invalid return type 'SolidObject **' for overloaded 'operator ->'	

Error	3	'Sprite' : is not a member of 'std::_Vector_iterator<_Myvec>'

Let me guess: this is an issue with pointers and how everything is stored in my vector...

For what its worth, I totally understand everything you guys are telling me. I get how a vector of pointers interacts with -> and I understand why we combine const and & in this context.
 

maharg

idspispopd
Sorry, it should be (*it)->Sprite. And yes, it's because the iterator acts like (or is) a pointer and then your value is a pointer.

I hope you're being careful about memory management with this vector, btw. You might want to consider using a shared_ptr as your storage type in the vector.
 
Status
Not open for further replies.
Top Bottom