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

shaowebb

Member
Fersis said:
In before programming Languages wars!


The only possible outcome of bringing up having a problem in any coding language.

EDIT: Also, I think Lynda.com has stuff for C++ tutorials. Could be wrong but it's worth a shot since they host about any other kind of coding tutorial.
 

AcciDante

Member
Man, I guess I'll just have to think over my classes again. Thanks for the helps guys. I'll probably be back in here later tonight...
 
AcciDante said:
Man, I guess I'll just have to think over my classes again. Thanks for the helps guys. I'll probably be back in here later tonight...

Well, just describe your actual problem instead of your proposed solution. We know your solution was something like "derive some classes here and there, make the Cat class implement a method called purr(), etc" But what was the original problem? What is your program trying to do?
 

AcciDante

Member
cpp_is_king said:
Well, just describe your actual problem instead of your proposed solution. We know your solution was something like "derive some classes here and there, make the Cat class implement a method called purr(), etc" But what was the original problem? What is your program trying to do?

Well the example pretty much summed it up. My derived class had functions that weren't declared in the base, and I was trying to call them off the base class pointer.
 

SaskBoy

Member
Can anyone help me with this code?

Code:
bool failed(data student, float &average)
{
 float AssignmentAverage= average(student.m_assignmentGrade,12);
 float LabAverage=average(student.m_labGrade,11);

 if(AssignmentAverage<50||LabAverage<50||0.5*(student.m_midterm+student.m_final)<50)
 {
  return true;
 }

 average=0.2*student.m_midterm+0.3*student.m_final+0.2*LabAverage+0.3*AssignmentAverage;
 return false;
}

There is more to the code than this but it all works as it should so I won't bother posting it. Just know I created a struct called data with members m_assignmentGrade and m_labGrade (both array's of float values).

I keep getting an error saying that average cannot be used as a function. The average function works as it should.

Any tips?
 

Kalnos

Banned
nelkon and parker said:
Quick guess... your argument name is average. Causing issues with the function name average.

this is it, it's a scope issue. I would just rename the parameter average that you're passing by reference.
 

SaskBoy

Member
nelkon and parker said:
Quick guess... your argument name is average. Causing issues with the function name average.

THANK YOU! I knew it was something simple but I couldn't figure it out!

:D
 
AcciDante said:
Well the example pretty much summed it up. My derived class had functions that weren't declared in the base, and I was trying to call them off the base class pointer.

I know, but that still has nothing to do with your actual problem. What program are you trying to write? What is your program supposed to do?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Or what the assignment is (assuming it's an assignment from a professor). What did he write down.
 

Heysoos

Member
Hey GAF, beginner here. Working on an assignment for class that deals with having to add, subtract, multiply, and divide fractions. The assignment calls for returning answers this way:
Example:please enter a problem: 1/2 + 1/4
The answer is 3/4


Now my question is, how do I return the answer this way(fraction form)?

In the header file I have the following function
Code:
int functionadd(int a, int b, int c, int d)
{
	int num, den, sum;

	num = (a * d) + (b * c);
	den = (b * d);
	sum=num/den;
	
	
	return sum;
}

And in the main I have this:
Code:
#include <iostream>
#include <string>
#include <cmath> 

#include "homework_4_head.h"

using namespace std; 

int main( )
{
	int numa, dena, numb, denb, result; //variable declaration
	char div; //dummy variable
	char operat; //Operator 

	welcome();

	cout<<" Enter your problem. "<<endl;
	cin >> numa >> div >> dena >> operat >> numb >> div >> denb;

	functionadd(numa, dena, numb, denb);
	result=functionadd(numa, dena, numb, denb);
	cout<<" The sum is "<<result<<endl;

	

	return 0;
}

Sorry if it's a little rough, trying to get it to work correctly before I start reducing and do the other functions, etc.
 

Chris R

Member
Just a small warning. Integer division behaves differently than most beginners think.

6/8 will result in 0, not the 3/4 you are wanting.
 

Heysoos

Member
rhfb said:
Just a small warning. Integer division behaves differently than most beginners think.

6/8 will result in 0, not the 3/4 you are wanting.

Yes, that's the problem I'm having basically. I'm not sure how to get around to getting the answer in x/y instead of the 0 I'm getting.
 

Chris R

Member
Heysoos said:
Yes, that's the problem I'm having basically. I'm not sure how to get around to getting the answer in x/y instead of the 0 I'm getting.
Well if you have your numerator and denominator, reduce the fraction (if you have to) and then return string that properly represents what the sum's value is. You won't be able to to do any arithmetic with the string, but it will look correct when printed out.
 

Slavik81

Member
Heysoos said:
Yes, that's the problem I'm having basically. I'm not sure how to get around to getting the answer in x/y instead of the 0 I'm getting.
You can't just return an integer if that's the case. The most sensible way of doing this would be to define a class or structure representing a fraction. Something like this:

Code:
class Fraction
{
public:
   int numerator;
   int denominator;
};

Then have your function add return a Fraction object, rather than an integer. Then, once its out of your addition function, you can print it however you want.
 

Heysoos

Member
rhfb said:
Well if you have your numerator and denominator, reduce the fraction (if you have to) and then return string that properly represents what the sum's value is. You won't be able to to do any arithmetic with the string, but it will look correct when printed out.

Thanks for the help everyone! Ended up just using this. Greatly appreciated. :)
 

Chris R

Member
Heysoos said:
Thanks for the help everyone! Ended up just using this. Greatly appreciated. :)
No problem, just realize that my solution isn't that great. Setting up a fraction class would probably be the best idea since it looks like you will be doing a lot of work with them.
 

painey

Member
is there anything more satisfying than figuring out a computer program? I am an IT major and taking python classes, and I just solved a bastard of a program assignment. When you press F5 to run, and it comes out perfectly.. its almost indescribable.
 

Heysoos

Member
Ok I'm back. :) Trying to reduce the fractions, but I think I'm doing it wrong.

Code:
void functiondivide(int a, int b, int c, int d)
{
	int num, den, remainder;
	int dividend, divisor;
	dividend = 0;
	divisor = 0;

	num = (a * d);
	den = (b * c);

	if(num>den)
	{
		num=dividend;
		den=divisor;
	}
	else 
	{
		den=dividend;
		num=divisor;
	}
	do{
		remainder = dividend % divisor;

			if(remainder != 0)
			{
			dividend = divisor;
			divisor = remainder;
			}
	}while(remainder =! 0);

	num = (num / divisor) * divisor;
	den = (den / divisor) * divisor;

	cout<< " " << num << "/" << " " << den <<endl;
	
	
	return;
}

Is there something wrong here? When I build it, it comes back with no errors, however, when I run it:
ueFSr.png

It does the same with the other functions. I think I'm doing the Euclid's algorithm wrong, but I'm not sure exactly what I'm doing wrong. :)
 
Heysoos said:
Ok I'm back. :) Trying to reduce the fractions, but I think I'm doing it wrong.
You're dividing by zero (divisor).

Just at a quick glance, shouldn't this:

Code:
if(num>den)
	{
		num=dividend;
		den=divisor;
	}
	else 
	{
		den=dividend;
		num=divisor;
	}
be this?
Code:
if(num>den)
	{
		dividend=num;
		divisor=den;
	}
	else 
	{
		dividend=den;
		divisor=num;
	}
 

Heysoos

Member
CrayzeeCarl said:
You're dividing by zero (divisor).

Just at a quick glance, shouldn't this:

be this?
Code:
if(num>den)
	{
		dividend=num;
		divisor=den;
	}
	else 
	{
		dividend=den;
		divisor=num;
	}

This got rid of the "stopped working" however, now it won't continue the rest of the commands. It stops doing anything once I enter the problem, so I suspect there's something wrong with the loop.
 

CrankyJay

Banned
lol the Homework 4 screenshot just messed me up. I thought I had a virus on my screen and was trying to click it. Need more coffee apparently.
 

Zoe

Member
Heysoos said:
This got rid of the "stopped working" however, now it won't continue the rest of the commands. It stops doing anything once I enter the problem, so I suspect there's something wrong with the loop.

Print to the screen as it's doing the calculation or use a trace to find out where it's hanging.
 

poweld

Member
Heysoos said:
This got rid of the "stopped working" however, now it won't continue the rest of the commands. It stops doing anything once I enter the problem, so I suspect there's something wrong with the loop.
Your while loop checks a very odd =! 0 instead of what you probably meant to use, != 0.

=! 0 means set the variable to the value of !0, which is the boolean true, or 1 (when converted to int).
!= 0 means check if the number is not equal to 0.
 

AcciDante

Member
Heysoos, do you use the debugger at all? I didn't know how to use it my first semester, but now that I do it's so helpful. Stick a breakpoint in your function and step through until you can find the line breaking your program.
 

Heysoos

Member
poweld said:
Your while loop checks a very odd =! 0 instead of what you probably meant to use, != 0.

=! 0 means set the variable to the value of !0, which is the boolean true, or 1 (when converted to int).
!= 0 means check if the number is not equal to 0.

I LOVE YOU:D I hadn't even noticed I had it set to =! 0. Changing it did the trick. :)! Thank you so much. I went over the code over and over and still overlooked it.

AcciDante said:
Heysoos, do you use the debugger at all? I didn't know how to use it my first semester, but now that I do it's so helpful. Stick a breakpoint in your function and step through until you can find the line breaking your program.

No. :/ Have yet to learn how to use it in the class. I'll see if I can learn how to use it myself slowly.
 

Zoe

Member
Heysoos said:
No. :/ Have yet to learn how to use it in the class. I'll see if I can learn how to use it myself slowly.

Like I said, printing out to the console can go a long way.
 

poweld

Member
Heysoos said:
I LOVE YOU:D I hadn't even noticed I had it set to =! 0. Changing it did the trick. :)! Thank you so much. I went over the code over and over and still overlooked it.



No. :/ Have yet to learn how to use it in the class. I'll see if I can learn how to use it myself slowly.
No problem, you'll get the hang of it.

You should certainly learn how to use the debugger. It's dead simple (assuming you're using Visual Studio) and will help you greatly in zero-ing in on problems like this.

Heysoos said:
What exactly do you mean by this? :)
Zoe means using some statements that print debug lines to help you "see" what is happening in your program. For example, just putting std::cout << "test" << std::endl; at the end of your loop would tell you that your loop is exiting after the first run, and that there's clearly something wrong with your loop test.

Outputting debug information is extraordinarily helpful, especially as your programs become more complicated. Our code base, for example, likely exceeds a million lines. If we didn't have a huge amount of debug messages spread throughout the code, we engineers would have a very tough time even beginning to locate the source of bugs.
 

Zeppu

Member
I have a programming related question. Not at all related to C++ but i guess all the real cool kids know C++ and seem to enjoy contributing to this thread and I don't want to create another thread for a specific question, so, on the other side of the spectrum, Java...

Anyone have any experience with Apache and JBoss? I have this problem at work which has been killing me and I would appreciate any help I can get.
 

Fitz

Member
Right, I've got what I think is a simple problem but I just can't figure out how to sort it.
What I'm trying to do is go through a char array one element at a time and grab any numbers and place them into a second char array (the second array also needs to be a char array because I'm going to put other letters into it later). The problem is when I try to do this I'm constantly getting strange characters output to the screen, kind of like an inverted "d".
Here's what the code pretty much looks like:

Code:
Assume that array1 is already holding the value ch33se, in the positions 0-5.

class example
{
     char array1[30];
     char array2[30];
public:
     void getNumbers()
          for (int i = 0; array1[i] != '\0'; i++)
          {
               if (isdigit(array1[i]))
               {
                    array2[i] = array1[i];
               }
     char* returnArray2()
     {
          return array2;
     }
};

int main()
{
example x1;
x1.getNumbers();
cout << returnArray2();

return0;
}

I'm sure the issue is something to do with the "array2 = array1;" line because everything else I've tested many times over and they work on their own.

EDIT: Small extra, I think the number of gibberish symbols is the unassigned positions in the array or something, I'd like to get rid of the 30 size limit on the arrays, which works for array2, but for array1 I get an "incomplete type not allowed" error.
 
Colkate said:
Right, I've got what I think is a simple problem but I just can't figure out how to sort it.
What I'm trying to do is go through a char array one element at a time and grab any numbers and place them into a second char array (the second array also needs to be a char array because I'm going to put other letters into it later). The problem is when I try to do this I'm constantly getting strange characters output to the screen, kind of like an inverted "d".
Here's what the code pretty much looks like:

Code:
Assume that array1 is already holding the value ch33se, in the positions 0-5.

class example
{
     char array1[30];
     char array2[30];
public:
     void getNumbers()
          for (int i = 0; array1[i] != '\0'; i++)
          {
               if (isdigit(array1[i]))
               {
                    array2[i] = array1[i];
               }
     char* returnArray2()
     {
          return array2;
     }
};

int main()
{
example x1;
x1.getNumbers();
cout << returnArray2();

return0;
}

I'm sure the issue is something to do with the "array2 = array1;" line because everything else I've tested many times over and they work on their own.

EDIT: Small extra, I think the number of gibberish symbols is the unassigned positions in the array or something, I'd like to get rid of the 30 size limit on the arrays, which works for array2, but for array1 I get an "incomplete type not allowed" error.


Problem 1: array2 is not initialized, and thus you are trying to print a string without a null terminator at the end.

Solution 1: Add the following function to the class declaration:

Code:
example()
{
    ::memset(array2, 0, sizeof(array2));
}


All that aside, this is honestly some fairly messy code, and there is almost certainly a better way to achieve what you're trying to accomplish, if you explain the problem at a higher level.


Problem 2: Since you are only copying the item into the other array if it is a digit, then this still will not work. The text in the first 6 characters, which you've said is ch33se begins with a letter, not a number. So the loop will copy nothing into positions 0 and 1, for example, nor into positions 3 and 4. What you end up with is something like this:

Array 1
c h 3 3 s e

Array 2
x x 3 3 x x

Here, I'm using x to represent a null terminator, not the letter x. In other words, nothing is in those positions.

Now, when you try to print array 2, it just stops because it encounters a null terminator immediately (after my modification anyway where you initialize the array to 0).


Solution 2: what you need to do is keep TWO SEPARATE COUNTERS. The position you are reading from, and the position you are writing from. What you want is for your array to end up like this:

Array 2
3 3 x x x x

Thus, the index that you write into cannot be the same as the index you read from.



Code:
     void getNumbers()
     {
          int in=0;
          int out=0;
          while (array1[in] != '\0')
          {
               if (isdigit(array1[in]))
               {
                    array2[out] = array1[in];
                    ++out;
               }
               ++in;
          }
     }
 

Fitz

Member
Ok that's brilliant, I knew the problem was something simple I just couldn't place it. As for the state of the code, it certainly isn't great on the whole, C++ is very new to me so I'm still in the process or learning really.
 

gblues

Banned
Colkate said:
Right, I've got what I think is a simple problem but I just can't figure out how to sort it.
What I'm trying to do is go through a char array one element at a time and grab any numbers and place them into a second char array (the second array also needs to be a char array because I'm going to put other letters into it later). The problem is when I try to do this I'm constantly getting strange characters output to the screen, kind of like an inverted "d".
Here's what the code pretty much looks like:

Code:
Assume that array1 is already holding the value ch33se, in the positions 0-5.

class example
{
     char array1[30];
     char array2[30];
public:
     void getNumbers()
          for (int i = 0; array1[i] != '\0'; i++)
          {
               if (isdigit(array1[i]))
               {
                    array2[i] = array1[i];
               }
     char* returnArray2()
     {
          return array2;
     }
};

int main()
{
example x1;
x1.getNumbers();
cout << returnArray2();

return0;
}

I'm sure the issue is something to do with the "array2 = array1;" line because everything else I've tested many times over and they work on their own.

EDIT: Small extra, I think the number of gibberish symbols is the unassigned positions in the array or something, I'd like to get rid of the 30 size limit on the arrays, which works for array2, but for array1 I get an "incomplete type not allowed" error.


You need a second counter for the array2 offset, because here's what your code does is this:
Code:
array1[] = { 'c','h','3', '3', 's', 'e' }
array2[] = { '\0','\0','3','3','\0','\0'}
I'm assuming you want:
Code:
array1[] = { 'c','h','3', '3', 's', 'e' }
array2[] = { '3','3','\0','\0','\0','\0'}
So, try this:
Code:
void getNumbers()
{
    int j=0;
    for (int i = 0; array1[i] != '\0'; i++)
    {
        if (isdigit(array1[i]))
        {
            array2[j++] = array1[i];
        }
    }
}
 

Fitz

Member
Got that all working now, I added in the second counter to determine the write location in the second array separate from the read location of the first array, which I can't believe I managed to mess up. Then added the function to initialize the second array which stopped the result displaying the empty array contents. Thanks for the help guys.
 

Zeppu

Member
I know you fixed it, but what I'd use is strcat instead of keeping a second pointer. Array1 and Array2 while technically arrays, are the standard/basic string format of C++ and there are tons of functions built around the char*, char[] strings.

Just make sure you always initialize the strings using memset, ZeroMemory or just = {\0}
 
Grr, why can't you be like Java C++

Anyway, I've got this class called point with a couple public methods

Code:
class Point
{
public:
	...

	const int x()
	{
		return x; // private var
	}

        const int y()
	{
		return y; // private var
	}

And this other class called Line which takes in points and uses it's x,y values to create the equation for the line

Code:
class Line
{
public:
	Line(Point p1, Point p2)
	{
		point1 = p1;
		point2 = p2;

		equation[0] = (point2.y()-point1.y())/(point2.x-point1.x());

I keep geting an error on that last line saying expression must have (pointer-to- ) function type
 
Zoramon089 said:
Grr, why can't you be like Java C++

Anyway, I've got this class called point with a couple public methods

Code:
class Point
{
public:
	...

	const int x()
	{
		return x; // private var
	}

        const int y()
	{
		return y; // private var
	}

And this other class called Line which takes in points and uses it's x,y values to create the equation for the line

Code:
class Line
{
public:
	Line(Point *p1, Point p2)
	{
		point1 = p1;
		point2 = p2;

		equation[0] = (point2.y()-point1.y())/(point2.x-point1.x());

I keep geting an error on that last line saying expression must have (pointer-to- ) function type
Why is p1 a pointer but p2 isn't? For pointers, you can't use the object.function() notation that way because the "." operator has precedence over the dereference operator (which you're also not dereferencing p1, btw). To call a method on a pointer, use "->" instead of ".". Also, you're not putting the parentheses after the "x" on point2.

Another thing - you need to cast everything as doubles or your division won't work. Dividing an int by another int will drop the remainder and won't round. Adding 0.5 will round them.

If point1, point2, p1 and p2 should be pointers, do this:

Code:
class Line
{
public:
	Line(Point *p1, Point *p2)
	{
		point1 = *p1;
		point2 = *p2;

		equation[0] = (double)(point2->y()-point1->y())/((double)(point2->x()-point1->x()) + 0.5;

If you don't want pointers, do this:

Code:
class Line
{
public:
	Line(Point p1, Point p2)
	{
		point1 = p1;
		point2 = p2;

		equation[0] = (double)(point2.y()-point1.y())/(double)(point2.x()-point1.x()) + 0.5;
 
Code:
class Line
{
public:
	Line(const Point& p1, const Point& p2)
		: point1(p1)
		, point2(p2)
	{
		equation[0] = (point2.y()-point1.y())/(point2.x()-point1.x());
...is the way a manly programmer would do it.
2jcpli.jpg


(of course, you'd have to change your "x()" and "y()" definitions to "x() const" and "y() const", but whatev)
 
1) Don't make member functions with the same name as member variables. You have x() and x, this is ambiguous to the compiler.

2) You're writing point2.x, but you mean point2.x().

3) Why return const int? You're returning by value anyway, it's not like the receiver can modify the result.

Also, word of advice: Don't use encapsulation just to say you used it. If you have methods called getx() and setx() and all they do is return x; and x = param; then what's the point? Just expose them publicly in that case.
 

usea

Member
cpp_is_king said:
Also, word of advice: Don't use encapsulation just to say you used it. If you have methods called getx() and setx() and all they do is return x; and x = param; then what's the point? Just expose them publicly in that case.
In case they're changed to do additional things later. Don't fight good practice.
 

Slavik81

Member
usea said:
In case they're changed to do additional things later. Don't fight good practice.
Indeed. Perhaps later you want to make X a part of an array, rather than having separate variables for each. Or the implementation is changed to make the class copy-on-write. Etc.
 
usea said:
In case they're changed to do additional things later. Don't fight good practice.

That's what everyone says, when was the last time you did that? Give a specific example, please.

You become a good programmer once you learn which of the "good practices" you can break, and when.
 

usea

Member
cpp_is_king said:
That's what everyone says, when was the last time you did that? Give a specific example, please.

You become a good programmer once you learn which of the "good practices" you can break, and when.
To what end are you breaking this good practice? To save 20 seconds typing? Betting on the fact that nothing will change. You sound like you have an axe to grind because somebody got a bit overzealous in preaching SOLID or something. There are measurable, actual benefits for this good practice and no reason to avoid it.

The benefits showed quickly when I started working with groups of people on software instead of just myself, and when the software I wrote lasted months instead of a weekly homework assignment.

The notion that you shouldn't bother to type out setters/getters because "what's the point?" is not a very well-reasoned one. When there's a dozen classes written by 3 different people that use those functions, you'll be glad they're there when requirements change.

I don't even do traditional business software or consulting, and I'm not really into the movements like agile. But even I can recognize the immense benefit.
 
usea said:
But even I can recognize the immense benefit.

To the person who originally asked the question about points: Sorry for derailing your question.

That being said, surely even you can realize what an immense overstatement that is? Immense benefits are things like LTCG or OOP in general. A freaking getter and setter is not an immense benefit.

It's a freaking point for christ's sake. I can pretty much guarantee you that if your get function is doing anything other than returning x in your extremely primitive point class, you have bigger problems to worry about.

But ok, I'll humor you for a second. Suppose you are making use of an external library that is optimized for, oh idk, SSE. It provides a function that transforms a 3 dimensional point by a transformation matrix. Since this is an external library and has no idea what your proprietary object hierarchy looks like, it simply exposes a function like this:

Transform(m11, m12, m13, m21, m22, m23, m31, m32, m33, *px, *py, *pz);

OOOOOPS.

"Aha!", you say. "You can simply provide a transform member function that has access to the internals of the class". Terrific. That is, of course, unless your code base is like every other code base in the world (i.e. imperfect). Oh *that* matrix. That one is in row-major order. Maybe I should make a TransformInRowMajor() function instead, or just add a bool to the end of my Transform() function that says which order to interpret the matrix in. (Hint: This is starting to get stupid). Maybe it's actually a 4x4 matrix but I only want to transform using the 3x3 matrix in the upper left corner. Sure would be nice if I could just access those pesky little x, y, and z variables.

Download any library in the world for doing 3D math that wasn't written by someone who was just eager to apply their hard-learned OOP concepts, and you'll see that points, like every other simple thing in the world that are just plain-old data, have their member variables public.
 

usea

Member
We weren't talking about a point class. I simply responded to what you said, which I disagree with. You shouldn't always drop get/set just because they have the most basic implementation. That's terrible advice.

The vector classes in my engine expose their members.
 
Status
Not open for further replies.
Top Bottom