JasonHippy 739 Practically a Master Poster

Well other than what's already been mentioned, reading as many technical C++ books as you can get hold of might also help.

I'm not going to mention any books here though because there's a sticky at the top of the C++ forum that has loads of book titles posted in it. I think most of the must-have C++ classics are listed there!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

The whole point of a constructor is to initialise any member variables in your class.
If members are not initialised correctly at construction, then you are at risk of inroducing all manner of bugs into your program.

So in your example, your default constructor for your mytype class should at least provide a default value for it's x member variable.

Take a look at this:

class mytype
{
public:
	double x;

	// provide a default initial value for x
	// in the default constructor
	mytype(): x(0.0){};
	mytype(double x1): x(x1){};

}

class myclass
{
public:
	mytype y;
	myclass(){};
	myclass(double z): y(z){};
}

NOTE: for the sake of brevity in this example I've made the member variables of both classes public, to save from having to create public get/set functions.

Now if you create an instance of your myclass class using the default constructor:
The default myclass constructor will use mytype's default constructor to construct its mytype member variable y.
Because the default constructor for mytype assigns a value of 0.0 to its member variable x, your myclass instance is fully initialised.

So in your main:

myclass mine;
cout << mine.y.x ; // should output 0.0

Likewise, if you use the overridden constructor which takes a double as a parameter, then your overridden constructor calls mytype's overridden constructor to construct it's y member variable.
So in main you could do this:

myclass mine(4.35);
cout << mine.y.x; // should output 4.35

Cheers …

JasonHippy 739 Practically a Master Poster

Despite working as a programmer for several years, I wouldn't consider myself an expert per se. I'm still learning new things every day. But I'd have to echo what niek_e said and say that the main thing you need on the road to becoming an expert is experience with the language.

Some kind of formal qualification or degree in an IT/Software related discipline would also help, but is by no means essential!
I'm getting along fine without a degree, but I do hold a vocational qualification in 'C', which actually helped get me into my first junior C++ programmer position.

Anyway, the main thing is experience.

Experience can be gained through:
Designing and writing your own applications - This goes without saying. Although, I find that debugging your own programs is the most useful experience of all!

Looking at open source code - Possibly even contributing some code to an open source project. Any code submitted to an open source project is usually scrutinised by several other members of that project. So they'll point out any flaws in your code/logic and will give you good pointers on how to improve your code.

Participating in forums - like here on daniweb. Beyond just posting your own problems, check out the C++ forums and take a look at the code other people are posting and try to solve their problems yourself...Even if you don't feel confident enough to post an attempt at a solution, take …

Nick Evan commented: *nods* +10
mrnutty commented: Thanks for the info +2
JasonHippy 739 Practically a Master Poster

Hi i am doing a program that has to add up the percentage for example if i get one question wrong it adds to the percentage and after i answer 20 questions i would get the final mark but i dont get why it doesnt work.

void multiplier(int difficulty)// function to multiply values
{
    int answer = 0;
    int num1 = 0;
    int num2 = 0;
    int rightanswer = 0;
    int total = 0;
    
    srand (time(0));

    for (int counter = 0; counter < 20; counter++)
    {
        
        if (difficulty == 1)
        {
            num1 = 1+rand()%9;
            num2 = 1+rand()%9;
        }
        else if (difficulty == 2)
        {
            num1 = 1+rand()%99; 
            num2 = 1+rand()%99;
        }
        
        rightanswer = num1 * num2;
        while(answer != rightanswer)
        {
            cout << "What is " << num1 << " * " << num2 <<"?"<< endl;
            cin >> answer;
            cout <<endl;

            if (answer == rightanswer)
            {
                rightresponse();
            }
            else
            {
                wrongresponse();
            }
            cout <<endl;
            total += answer;//  add the answer to total value
        }// end while
    }//end for
     evaluate(total);


void evaluate(int total)
{

    int percent;
    
    percent = total / 20 * 100;
    cout << "Percentage is " << percent << "%"<< endl;
    
    if (percent < 75)// if the percentage is less than 75
    {
        cout << "Please ask instructor for extra help" << endl;
    }
    else // if greater than 75
    {
        cout << "Well done! " << endl;
    }

}

There are several problems I can see in your code.

This is one of them:

total += answer;// …
JasonHippy 739 Practically a Master Poster

Hi all, and must say a great looking forum!

I wish to start developing c++ apps on Linux and would like to know what GUIs are supports out of the box on Linux, especailly the main distros anyway? QT, KDE, GTK, etc? I basically want to write gui apps that will run on linux and not need additional libraries installed, GTK on Fedora is one example I've come across before! Of course I always think along the lines of the most simple and unknowledgeable of users trying to use my software :icon_rolleyes:

I've recently started looking into this myself...
With regard to out of the box GUI functionality:
AFAIK It depends on the desktop/window managers a linux distro uses:
e.g. Kubuntu, OpenSuse and PCLinux use KDE desktop manager.
Ubuntu and Fedora use Gnome desktop manager.

GTK+ 2.0 is currently the default out of the box GUI library for the Gnome desktop. QT is the default for KDE. Not sure which libraries Xfce, fluxbox and all the other linux desktop/WMs use.

As for other GUI libraries, wxWidgets is the main one of any notability. wxWidgets is cross platform and is supposed to use whatever native UI elements are available for the platform it's running on. But I have a sneaky suspicion that on linux, wxWidgets uses GTK+ widgets for UI by default, regardless of the desktop manager.

If you developed your app with QT, any Gnome users who don't have any other QT apps …

JasonHippy 739 Practically a Master Poster

Your GetData and GetSize functions need to be declared const
e.g.

unsigned GetSize() const // This
	{
		return n;
	}
void* GetData() const // and this needs to be const
	{					
		return v;
	}

Because the parameter 'a' to the Allocate classes operator = override function has been declared as a constant reference to an Allocate object, then the GetData and SetSize functions have to be declared as const otherwise the compiler thinks that they might attempt to modify the Allocate object....If you follow me!

Cheers for now,
Jas.

edit:
Dammit, beaten to the punch again!

JasonHippy 739 Practically a Master Poster

I think that learning about tweening is a great idea, you should do it! heh heh!

When used properly tweening can make your animations look a lot more natural, realistic and life-like.

There are some great free tweening libraries available for AS3 (like tween lite http://blog.greensock.com/tweenlite/ ) which are actually more powerful than the built in tweening classes (and easier to use as well!)

Regarding your preloader question...Google it, there are loads of tutorials about creating flash preloaders all over the web (or at least there were the last time I looked). You certainly don't need to go buying a template! Why do that when you can create one yourself?!

The bar and % loaded indicators are quite straightforward to create, but there's nothing to stop you from doing something more elaborate while the file is loading.

I recommend that you do the following:
1. Take a look at some preloader tutorials (even if they are sucky bar and % indicators)
2. Understand exactly what they're doing and how

Once you've done that and you understand how they work, you can use that knowledge to create your own preloader...If you like you can make a monkey breakdance while the file loads, it doesn't have to be a bar and a %loaded indicator.
The only reason most flash files use simple bars and % indicators is to ensure that the preloader part of the .swf loads and starts running really …

iamthwee commented: I'll second this. +11
JasonHippy 739 Practically a Master Poster

If you want to take the free software route, you could try Scribus.
Scribus ( available from http://www.scribus.net) is a cross platform and free, open-source desktop publishing app which is ideal for creating pdf documents.

I've got it installed on all of my Windows and Linux PC's both at work and at home. I've not used it too much yet, but it seems to do the job!

Offhand that's about the only freeware I can think of, other than OpenOffice.

But there are several commercial DTP/PDF editing programs out there like MS Publisher (as pointed out by H12Japan), though you'd probably have to use it in conjunction with PDFCreator as I don't think publisher can output directly to pdf.
Having said that, if you install PDFCreator you can output pdf from any windows application that allows printing, including your preferred DTP package.

The only other commercial programs that I can think of for direcet pdf layout and creation are Acrobat pro from Adobe (the original creators of the pdf format!), and Pagestream (http://www.pagestream.org/)

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Well there's more than one way to do this, so how you're creating objects and placing them on the stage at the moment will determine the best way of going about things!

It would really help if we could see some of your code or better still your .fla.
Are you using instances of sprites/movieclips that have been dragged onto the stage from the library in your .fla? Or are you adding instances to the stage using only code? Or a mixture of both?

If you post some relevant code, we might be able to help!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Hi,

I hope this is the right place for this question.
What program can I use to make nice looking .pdf files from Word documents?

Thanks

There's a free tool called PDF Creator (http://www.pdfforge.org/) which allows you to print your word documents to .pdf.
(In fact you can print from pretty much any app to .pdf!)

After installing PDF Creator (which installs itself as a virtual printer):
1. open up your word document
2. go to file->print
3. In the print dialog, select PDFCreator from the list of printers and select OK.
4. PDFCreator will then pop up a window which will ask you to fill in some details about your .pdf - fill in anything you feel you need to and then click on save.
5. A save dialog will pop up. In the save dialog select the location you want your pdf file to be exported to.
6. A password dialog may pop up (depending on the settings of PDFCreator), this will enable you to password protect the owner part of the PDF. Enter a password in the two boxes here and click OK and that's it, your .pdf will be exported.

To alter the settings of PDFCreator, open up the PDFCreator executable (which brings up a print monitor window) and select 'printer->options' from the menu (or press CTRL+O). It also comes with a pretty comprehensive .chm help file too.


Other than that …

JasonHippy 739 Practically a Master Poster

Hey Tonka!

Wouldn't it make more sense to use a structure (struct) to store the name, age and score for each person and then use one array of structures instead of three separate arrays?
That way you only have to sort one array.

In fact if you use a std::vector instead of an array things become even easier. You can use the std::sort() function to sort the vector. All you need to do is create at least one comparison function for the std::sort function to use.

Take a look at this example which uses a struct, a std::vector and std::sort:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iterator>

// here's our data structure
struct data
{
	std::string name;
	unsigned int age;
	unsigned int score;
};

// Function definitions...

// These are the comparison functions we'll be using later with the 
// std::sort method...
bool sortVecByNameAscending(data &d1, data &d2);
bool sortVecByAgeAscending(data &d1, data &d2);
bool sortVecByScoreAscending(data &d1, data &d2);
bool sortVecByNameDescending(data &d1, data &d2);
bool sortVecByAgeDescending(data &d1, data &d2);
bool sortVecByScoreDescending(data &d1, data &d2);

// we'll use this to output our data.
// takes a string message and a vector of data objects
// as parameters. 
void outputData(const std::string &msg, const std::vector<data>& dat);


// Here's the main function...
int main()
{
	//Create a vector to store some data
	std::vector<data> userData;

	// I'm just gonna create an instance of the structure and manually 
	// add some of your posted data to the vector using push_back
	data dat;
	dat.name="John";
	dat.age=23;
	dat.score=1; …
JasonHippy 739 Practically a Master Poster

Hmm, I'm not sure offhand!
I've had a brief tinker with capturing microphone input from flash using AS3, but I've not done anything much with it yet so I'm not entirely sure of the full range of capabilities. But I plan on taking a more detailed look at some point!

A while ago I was planning on creating a vocal training game for singers where flash plays a note or a series of notes which the player has to sing back. The game then analyses and gives feedback on the accuracy of the players response...But then I started messing with motion detection/motion capture and on the fly image processing using a webcam and flash/AS3! And I've been having way too much fun! heh heh! ;)

Consequently I haven't done anything with the singing game idea!

But if I do find anything out I'll let you know!
Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Take a look at this page:
http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx

Assuming that the other processes you mentioned are programs that you've written and as long as I understood the above page correctly, if you set the code for all of your programs/processes to open data files using this syntax:

FileStream^ fs = File::Open( path, FileMode::Open, FileAccess::Write, FileShare::None );

or:

FileStream^ fs = File::Open( path, FileMode::Open, FileAccess::Read, FileShare::None );

That should stop other processes from being able to open the same file. I imagine there will be an exception thrown by any attempt to open a locked file, so if your processes are also set up to catch any relevant exceptions that might also help things along!

So any time your programs need to open a file for read/write, try opening with the above code. If an exception is thrown, perhaps set up some kind of timer for a few milliseconds and then try opening the file again.
If all of your processes are doing this, then I guess you can be sure that the only time your processes will be able to use the file is when none of the others are using it!

Not sure if that's any help, I've not done any managed C++ in donkeys years. But from an initial glance that's how things look to me!
Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

My crystal ball says the UNICODE macro is defined, which causes CString to resolve to an actual type of CStringW. The implicit conversion ends up actually being CStringW to wchar_t*, which cout (the narrow stream object) isn't built to handle. Two simple options are to undefine UNICODE (if you don't need Unicode in the project), or use wcout instead of cout.

Aha, thanks Narue, that was beginning to bug me!
I've not done anything much with unicode, so I've never come across that particular problem before. But I guess that would make sense!

I shall endevour to remember that for future reference.

Thanks again,
Jas.

JasonHippy 739 Practically a Master Poster

Hmm, That's very odd!
After looking into this, Niek e's example compiles ok for me and outputs the strings properly.
I'm not sure why you're seeing the addresses of the columns instead of the actual strings..

What happens if you explicitly cast the result of the 'your2darray.at().at()' function call to a CString?
e.g.

std::cout << (CString)(your2darray.at(y).at(x)) << " | ";

That's about the only thing I can think of right about now.
If that doesn't work, I'm at a loss I'm afraid!
Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

The reason you're not getting any output is because by the time you've got to the end of the Life function, all of your original generation of bacteria are utterly annihilated, dead, gone, pushing up the daisies, wormfood! heh heh! :)

The problem is this section of code in your life function:

...
void Life(bool bacteria[][COL])
{
     bool nextGenbacteria[ROW][COL];
     int neighbors=0;
     int neighborsDead=0;
     
     for(int row=0;row<ROW;row++)
     {
      for(int col=0;col<COL;col++)
      {
       if(bacteria[row][col]==true&&bacteria[row][col-1]==true)
       {
...

The two counter variables 'neighbours' and 'neighboursDead' have been declared before the two nested for loops.

As a result of this, the counters are global to both for loops and the counters are incrementing upwards during each iteration of the loops. So before the first iteration, the value of neighboursDead is 0, but by the final iteration the value of neighboursdead has counted up to something like 49.

Basically the counters are storing the total number of neighbours and dead neighbours for all iterations so far (So it incrementally stores the numbers for every single row and column).
Because of this, in accordance with your rules of life, all of your bacteria are being annihilated.

What you really want to be doing is counting the neighbours and dead neigbours for each column of the current row and then reset the counters before counting those in the next column.
So you need to ensure that both counters are reset each time your second loop reiterates.
If you move their declarations down …

JasonHippy 739 Practically a Master Poster

OK, if you need a fresh pair of eyeballs to go over the code, .zip up all of the source files for your project and post it here as an attachment, I'd be more than happy to take a look at it for you!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Hey there!

If I am following you correctly, one thing you could do I suppose is put two instances of your object onto the stage and use the bottom one as a placeholder (so it's not drag enabled.).
That way, when the user drags the top object off, there is an image underneath which makes it look as if there are more draggable objects on the stage underneath the one you're currently dragging.
If you grey the placeholder out, it makes it look as if the item has been disabled until the current drag operation has finished.

Once the current draggable item has been dropped into place, you can create a new draggable item over the top of the placeholder.
Or alternatively, if your draggable item disappears after it has been dragged and dropped, you can simply reset the draggable items position so it's placed directly over the placeholder (That way you'll only ever need one draggable object!).

As another alternative, if you know how many draggable objects you're going to need, you could stack several instances of your draggable objects on top of one another on the stage (use an array in your code) and get the user to drag 'em off one by one until the stack is empty.

So there are several different ways around it, it just depends exactly what you're after!

Cheers for now,
Jas.

P.S.
If this was of little or no help …

JasonHippy 739 Practically a Master Poster

Using strings would be preferable. However, if this is for an assignment and you have to use c style strings; in your function you could copy the original string into a 2nd character array. Then parse through the 2nd array and copy any characters that are not 't' or 'T' back into the 1st. Once you've got to the end of the 2nd array, append a null on the end of the first array and you're done!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

It's literally just this...

void withdraw(double amount)
	{
		balance -= amount;
	}

I'll attach the file that this is done in but I'm nearly 100% sure it's not this method because when used with a vector this did the job

Hmmm, that's odd. That looks like it should correctly update the objects balance. Have you tried using the this pointer to refer to the balance?
e.g.

this->balance -= amount;

That might just do the trick!
If that doesn't work (and I can't see why it shouldn't!), I also noticed that in your constructor you're setting the balance using:

Account::balance = balance;

So perhaps as a last resort you could try adjusting the balance like this:

Account::balance -= amount

Other than that, I can't see anything obvious there!
Cheers for now,
Jas

JasonHippy 739 Practically a Master Poster

OK, well take another look at your code...
When the Bank::withdraw function is called, a pointer to the relevant account is obtained. If the account balance is >= the amount, then the withdraw function is called for the account pointed to by the account pointer.

Therefore if the accounts balance is not getting adjusted when Bank::withdraw is called then your problem is actually in the Account::withdraw function.
So there's nothing wrong with any of the code you've posted here. The problem is in Account::withdraw. Therefore the question is what does the Account::withdraw function look like? (You haven't posted it!)

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Personally I'd copy the sentence into a stringstream object and then use the stringstream's >> operator to separate each word from the sentence and store each word in a vector of strings.
Like this:

#include<iostream>
#include<sstream>
#include<string>
#include<vector>

using namespace std;

int main()
{
	string sentence, word;
	vector<string> wordlist;
	stringstream raw_stream;

	// Get user to enter a sentence:
	cout << "Enter a sentence: ";
	getline(cin, sentence, '\n');
	cout << endl;

	// Copy the sentence into a stringstream object	
	raw_stream << sentence;

	// Separate the sentence into individual words 
	// with the >> operator and put them into the wordlist
	while(raw_stream >> word)
		wordlist.push_back(word);

	// Output the contents of the wordlist 
	if(wordlist.size()>0)
	{
		cout << "In the sentence:" << endl << sentence << endl;
		cout << "The individual words are:" <<	endl;

		int count=1;
		for(vector<string>::iterator iter = wordlist.begin(); iter!=wordlist.end(); iter++)
		{
			cout << "Word " << count << ": " << *iter << endl;;
			++count; 
		}
	}
	else
		cout << "No words were entered!" << endl;

	// wait for user to press enter
	cout << "press enter to continue..." << endl;
	getline(cin, sentence, '\n');
	return 0;
}

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Personally, I'd leave only the declarations of the member variables and functions for your class in the header file and then put the definitions of the functions into a .cpp file which has a filename that corresponds with the header. (e.g. particle2.h and particle2.cpp)
Your get and set functions will probably be ok defined in the header as they are pretty small, but all of the other functions should be declared in the header and defined in the .cpp file.
So your header would look something like this:

// This is particle2.h
// Add whatever includes you need here
// At the moment none are needed, but I guess you may have other functions in here which use vectors etc.!

// Note: If you do have any functions which take other datatypes/classes as parameters
// you might not need includes here, you can forward declare classes like this:
// class std::vector; // forward declares the std::vector class
// once you've forward declared something, you should #include its header in your .cpp file
// Also Note: Sometimes forward declaring doesn't work, so you might have to include the header here instead of forward declaring!
// Offhand I can't remember the golden rule with regard to forward declaring things!

// inclusion guards - ensures this header is only included once.
#ifndef PARTICLE2_DEFINED
#define PARTICLE2_DEFINED

class particle
{
	// private data
	double x;
	double y;
	double z;
	double q;
	double m;
	double ux;
	double uy;
	double uz;
	double hux;
	double …
JasonHippy 739 Practically a Master Poster

I've had a bit of a new album frenzy recently, so I've been listening to lots of new music...Those of you who know me will be unsurprised to know that they were all metal!

I picked up the recent albums by Behemoth, Cannibal Corpse, Slayer, Megadeth, Nile and Alice In Chains.

Here are my thoughts for any daniweb metallers out there:
The Cannibal Corpse (Evisceration Plague) and Slayer (World Painted Blood) albums are pretty much your standard fare for these two bands.

Cannibal Corpse have in the past been referred to as the AC/DC of death metal, because you always know what you're going to get from them...And I guess by that token Slayer must be the AC/DC of thrash. There are no instant classics on either of these albums. No new 'Hammer Smashed Face's, or 'South of Heaven's, but they are solid albums nevertheless.

Although I am left wondering what happened to Slayers guitar tone on WPB...Is it me or does it seem a bit weaker in the mix than before? Anyone else noticed that? or is that just me? The guitar tone is way different!

The Nile (Those Whom The Gods Detest) and Behemoth (Evangelion) albums are brutal as hell. Just as you'd expect from these two bands! Again, I don't think there's anything groundbreaking on them; but they are good, solid technical death metal albums with some amazingly fast blasts and double bass footwork!

The new Megadeth album (Endgame) is …

JasonHippy 739 Practically a Master Poster

Flash sucks
flash intros penalise in search, annoy your customers
anything that makes the page load longer, kills customer retention

heh heh, aside from that and actually staying on topic..heh heh!

I've never used after effects, so I couldn't comment on its functionality, but it's certainly possible to do an intro like that in flash. But you'd have to be bloody good to get something that looked as flashy looking as that behemoth of an intro!

That was a very professionally made intro..But its a shame it took so long to load...It should be noted that the flash intro you linked to there was more the kind of thing for use in a video presentation, a desktop flash app or perhaps a LAN based site rather than a web based flash site, it even said so on the web page.

If you're planning on doing an intro like this for a video presentation or a desktop flash app, then you should be OK, go ahead and give it a shot, the sky's your limit!

However; if you're doing this as an intro for a website, then you'd probably be better served doing something more optimised. As bob has already pointed out, if your intro doesn't load quickly, then potential users of your site will just leave...They won't wait!
Likewise, if the intro is too long (and especially if there's no 'skip intro' button), your users will just leave...unless the intro is really REALLY …

JasonHippy 739 Practically a Master Poster

Ah, hello again Narue.
Once more you've quite correctly corrected me on my half-witted absent-minded inaccuracy!

>conio.h is an older c header file and is deprecated in C++...
Please don't use deprecated to mean anything except "standard, but not recommended because it might not be standard in the next revision". conio.h was never standard, either in C or C++.

Oh yes, of course {memory kicking in..albeit slowly!} I forgot about that...conio.h was the dos specific implementation for various console related IO things wasn't it? kinda like curses in *nix. Sorry, it's been quite a long time since I did any pure c stuff! Either way it's bad to use it in C++, so I was at least half right, but perhaps I worded it badly!!

>There is an equivalent C++ header to access the same functionality as conio.h
No, conio.h provides functionality that isn't portable, and is thus unavailable in the standard library. However, you can get close for things like getch. cin.get can "pause" the program just as well[1], with the added restriction of the user having to press the enter key:

No, you're right there isn't....I think I was thinking of stdlib.h and <cstdlib> or something! I'd put it down to a blonde moment on my part. And yes, I am blonde...Or at least I would be if I had any hair left! heh heh! ;)

Anyway, thanks for the correction. Consider me well and truly spanked!
Cheers for now,

JasonHippy 739 Practically a Master Poster

I'v also been told I need to complete the program using referencing, which I do understand but I couldnt get working?

OK, try this on for size, this uses references as parameters to the two functions..

#include <iostream>

using namespace std;

/////////////////////////////////////////////////////////////////////
/// Get a value from the user and store it in the passed in reference
/////////////////////////////////////////////////////////////////////
/// \returns<void>
/// \param<num> reference to an int
/////////////////////////////////////////////////////////////////////
void getNumber(int &num)
{
	cout << "Enter a number: ";
	cin >> num;
	cin.ignore();
}

/////////////////////////////////////////////////////////////////////
/// Make input value (passed in reference) even
/////////////////////////////////////////////////////////////////////
/// \returns<void>
/// \param<number> reference to an int
/////////////////////////////////////////////////////////////////////
void makeEven(int &number)
{
	// if number entered was not odd, get a new value
	while(number%2!=1)
	{
		cout << "Number must be odd!!" << endl;
		getNumber(number);
	}
	// number is odd so decrement it
	--number;
}

 
int main()
{
	int x = 0;
	// get initial value for x
	getNumber(x);

	// make it even
	makeEven(x);

	// output the value
	cout << "Number is now: " << x << endl;

	// wait for user to press enter...
	cin.get();
}

So looking at main, we're creating an int variable called x.
We pass x into getNumber() as a reference.
getNumber prompts the user to enter a value which is stored in x.

Back in main we call makeEven and pass x as a reference.
Inside makeEven, if the passed-in number is even, getNumber is called until the input value is odd.
Once we have an …

JasonHippy 739 Practically a Master Poster

OK, well for starters you don't want a goto in makeEven, you want to return something....
Also in main you'd need to assign the value of x to the value returned by a call to makeEven(x).

That gives you this:

#include <iostream>

using namespace std;

int makeEven(int x)
{ 
	if ( x % 2 != 0 ) 
		return x-1;
	else
		cout<<"Please enter an odd number!";

	return 0; // must return something here
}

int main()
{
	int x;

	cout << "Please enter an integer: ";
	cin >> x;

        // call makeEven and assign the returned value to x
	cout << "Your number is now: " << makeEven(x) <<endl; 
	
}

Although, as you've correctly pointed out. It would make sense to repeatedly prompt the user to enter an odd integer until an odd integer is entered before calling makeEven. But then makeEven would be pretty much redundant as it would only need one line of code:

#include <iostream>

using namespace std;

int makeEven(int x)
{ 
	return --x;
}

int main()
{
	int x;
	bool isOdd=false;
	while(!isOdd)
	{
		cout << "Please enter an integer: ";
		cin >> x;
		cin.ignore(); // ignore the newline from the previous input
		if(x%2!=0)
			isOdd=true;
		else
			cout << "Please enter an odd number!" << endl;
	}
	
	cout << "Your number is now: " << makeEven(x) <<endl;
 	cin.get(); // press return to continue...
	
}

Which is pretty pointless, but perhaps you could put the entire input and process stage into one function, so your code …

JasonHippy 739 Practically a Master Poster

From looking at the code, it seems to me that if you run your debugger and step through the program you'll find that line 34 will fail to read anything from the input file.

The reason for this is because by this point you've already read the entire file, so your input stream inData is pointing to the end of the file. So what you need to do is reset inData to point to the start of the file.
If you close the input file and then reopen it again between lines 32 and 34, that should achieve the desired effect.
There are probably other ways, but I can't think of any offhand!

However, the failure to read from the file is the least of your problems.
Once you've fixed the read problem, when your call to ReverseQueue is made, your program will get stuck in infinite recursion. Your program will recursively call ReverseQueue until the program runs out of memory and crashes.

Your program does not fulfil the criteria you need to meet, it doesn't reverse the queue, so you're going to need to rethink your program logic.

Wouldn't it make sense to read your input file once, sending the values into an instance of your queue class? Then perhaps iterate through your queue to output the original values to the output file before passing your queue to a recursive function to reverse the queue, before finally outputting the final values to …

JasonHippy 739 Practically a Master Poster

Glad to have helped! :)

JasonHippy 739 Practically a Master Poster

Oh I see you've HAD to implement your own queue class as a part of your assignment...sorry I thought you were just over complicating things for yourself.

In that case, to turn your class into a double ended queue I guess you'd need to implement a function to allow the removal of items from the back of the queue, something like this perhaps?

template<class Type>
void queueType<Type>::deleteBackOfQueue()
{
     if (!isEmptyQueue())
     {
       count--;
       queueRear = (queueRear - 1) % maxQueueSize;
     }
     
     else
     cout <<"Cannot remove from an empty queue"<<endl;
     
}

Then in the if statement:

if(aDeque.front() == aDeque.back())		
{			
	aDeque.deleteQueue();	
	if(!aDeque.empty()) 			
		aDeque.deleteBackOfQueue(); // pop the back()		
}

I've not compiled or tested the above code snippets, but I'd imagine that you would need to be doing something similar to the above!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

dkalita has already explained it to you...Try reading his post again!

The function 'fun' returns an int.
But it takes a pointer to a function as a parameter.
The function pointer must point to a function which returns an int and takes no parameters.

main happens to be a function, it returns an int and it takes no parameters, so you can easily pass a pointer to main into the function. Even from within main!

Function pointers do have their uses and I've never seen a function which took a pointer to main as a parameter, but I guess there may be some practical applications, perhaps some recursive algorithms might call for something like this.

I've expanded on the example you posted. This little doozy uses a function pointer to implement recursion:

#include <iostream>

using namespace std;

// function declaration
int myFunction(int (*funcPtr)());

// global static int to stop us from recursing too far
static unsigned int count=0;

int main()
{
	cout << "inside main" << endl;

	// now we'll call our function passing a pointer to main
	myFunction(main);
	
	cout << "exiting main" << endl;
	return 0;
}

// myFunction:
// calls a function pointed to by the input parameter (a function pointer)
// \returns<int>
// \param<funcPtr>takes a pointer to a function which returns an int but takes no parameters
int myFunction(int (*funcPtr)())
{
	cout << "inside myFunction!" << endl;

	// increment the counter
	count++;
	// if count is less than 3:
	if(count<3) …
JasonHippy 739 Practically a Master Poster

It seems to me that you are over complicating things. Wouldn't it be a lot simpler to just use a double ended queue, otherwise known as a deque?
Modifying your code from one of your previous posts in another thread:

//Implement the palindrome-recognition algorithm described in "Simple Applications of the ADT Queue"

#include <iostream>
#include <string>
#include <deque>

using namespace std;

void isPal(string);

void isPal(string s)
{	
	deque<char> aDeque;

	for(unsigned i = 0; i < s.length(); i++)
	{	
		aDeque.push_back(s[i]);
	}
	
	bool charEqual = true;
	
	while (!aDeque.empty() && charEqual==true)
	{
		if(aDeque.front() == aDeque.back())
		{
			aDeque.pop_front();
			// as long as the pop_front() didn't empty the deque..
			if(!aDeque.empty()) 
				aDeque.pop_back(); // do a  pop_back()
		}
		else
			charEqual=false;
	}
	
	cout << word;
	if(charEqual == true)
		cout <<  " is a Palindrome" << endl;
	else
		cout << " is NOT a Palindrome" << endl;
}

int main ()
{
	string input;
	cout << "Enter the string: ";
	cin >> input;
	isPal(input);

    return 0;
}

Isn't that a lot cleaner and quicker than using two queues? it certainly saves you from creating that unneccessary template nonsense in queue.h!

EDIT:
Now modifying the above code to read words/lines from a file and then pass each word/line to the isPal() function you get this:

//Implement the palindrome-recognition algotithm described in "Simple Applications of the ADT Queue"

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <deque>

using namespace std;

bool isPal(string);

bool isPal(string s)
{	
	deque<char> aDeque;

	for(unsigned i = 0; i < s.length(); …
JasonHippy 739 Practically a Master Poster

The thing that's confusing me is how you're getting a syntax error from a data-file!!

How are you running the program and passing the parameters? Are you running it from the command line? or from inside the VS2008 IDE?

I've just compiled and tested your code in g++ / codeblocks on Linux and ran your program from both the command line and from the IDE and it accepts the data file and runs without error.

I don't have a windows machine in front of me so I can't fire up VS and test it. I'm at home ATM and although we do have a windows pc in our very cold kitchen; Brrrr, I'm not going out there! heh heh!

Have you tried running it from the command line?
1. Open up a command window
2. Navigate to the folder with your .exe in it and enter the following line:
yourprogram.exe input.txt
(obviously replace yourprogram.exe with the name of your .exe!)

Otherwise, if you're trying to run the program from the VS2008 IDE, Somewhere in the project properties page on the debug tab/page, you can set any command line parameters.
If this is what you're already doing, perhaps try changing the value to input.txt instead of using ./input.txt.

Other than that, I'm not really sure what the problem can be!
The fact that the error mentions a syntax error leads me to believe that the compiler is attempting to …

JasonHippy 739 Practically a Master Poster

Yup, as suspected; logical AND is evaluated left to right, so if the 1st condition fails / is false, then the 2nd condition is ignored and the logical AND operation returns false. The 2nd condition is only evaluated if the 1st condition is true.

So my original post should be fine!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

If memory serves, if the left hand condition fails it won't bother evaluating the right hand one.
(depending on how the AND is evaluated...I think it gets evaluated left to right, so I'm pretty certain that if the first condition fails, it will ignore the 2nd condition and just return false! However if it is evaluated right to left, then you could simply swap the conditions over!)

Alternatively if your code is in a function you could do this:

Point* MyPoint = Object->GetMyPoint();

// if pointer is not valid, return...
if(!MyPoint)
    return with an error condition/value;

// if we get this far, the pointer is valid
if(MyPoint->GetValue() != 2)
    call function A;
else
    call function B;

return success condition/value;

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

If I have the following setup:

Point* MyPoint = Object->GetMyPoint();

if(MyPoint->GetValue() != 2)
  do something;
else
  do something else;

If MyPoint is NULL or invalid, the MyPoint->GetValue() will cause a segfault.

This should fix it:

Point* MyPoint = Object->GetMyPoint();
if(MyPoint)
{
  if(MyPoint->GetValue() != 2)
    do A;
  else
    do B;
}
else
  do B;

But that is quite awkward, as it makes me repeat B and it adds an extra nested layer.

Is there a better way to do this?

Thanks,

Dave

This would be the simplest way of doing it:

Point* MyPoint = Object->GetMyPoint();
if(MyPoint && MyPoint->GetValue() != 2)
    do A;
else
    do B;

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

You might want to take a look at this thread:
http://www.daniweb.com/forums/thread230230.html

The first few posts are irrelevant, but the later posts are probably more or less exactly what you're looking for!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

It's because the literal value (25.95) that you are passing into your call to the function VAR1 is automatically treated as a double, but your function takes a float as a parameter. So you're getting a warning about it.

If you pass the variable like this:

printf("%.2f", VAR1(25.95f)); // printf a float ending in .95

The f at the end of the literal value will ensure that the value is treated as a float and not a double and should stop the warning from occurring.

in fact considering this is C++ you should really be using std::cout instead of printf in line 15 too! :

cout << setprecision(.2) << VAR1(25.95f);

Note: in order to use setprecision with cout, you also need to include iomanip after iostream..:
So after you've included iostream, add the following:

#include <iomanip>

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Aha,
I've just fired up one of my linux boxes, I've created a project in codeblocks using your files. I've made my suggested changes and and tried compiling... And there are still compiler errors.

The problem seems to be regarding the base class members (from ArrayQueue.h) in the Deque class. For some reason g++ doesn't seem to recognise the protected members from ArrayQueue.h like front, back, count, items etc.

I'm not sure if there's a compiler switch to enable the compiler to recognise these correctly, but I've found that if you reference the base-class members using the 'this' pointer in Deque.h, then the compiler errors disappear.

Here's a snippet from Deque.h to show you what I mean:

template <class T>
bool Deque<T>::dequeueBack(T &itemRef){
	if (this->isEmpty()){//cannot dequeue
		//cout<<"Empty dequeueBack in Dequeue\n";
		return false;
	}
	else{//procede dequeuing
		itemRef= this->items[this->back];
		if (this->back==0)
			this->back = MaxQueue-1;
		else
			this->back--;

	}
	this->count--;
	return true;
}

Anyways, the program now compiles without errors or warnings on windows and *nix. A .zip is attached with my changes applied.

In order to ensure that my changes haven't introduced any bugs to your code (apologies if any have crept in there!); you might want to ensure that the program still works in the way you originally intended it to.

Cheers for now,
Jas.

[EDIT]
p.s. I'm fairly new to *nix programming myself...Up until recently I've only ever developed on Windows (so yes, I'm a bit wintarded!). The little *nix programming …

JasonHippy 739 Practically a Master Poster

Can Someone tell me why these files won't compile on unix but work fine (mostly) in windows?

It looks like unix-land doesn't load the variables from the inherited class QueueArray into the proper scope.

prog5.cpp is supposed to create 3 different types of Deque classes.
each Deque inherits from ArrayQueue

Your help is greatly appreciated =)
Thanks everyone

One thing that immediately strikes me is that you are using #pragma once, which as far as I am aware is a preprocessor command that is used solely by Microsoft compilers. So perhaps using traditional inclusion guards might help here. e.g.

#ifndef SYMBOLNAME_DEFINED
#define SYMBOLNAME_DEFINED

// The rest of your header code goes here

#endif // SYMBOLNAME_DEFINED

I'm thinking that because gcc doesn't recognise the #pragma command, it therefore sees no inclusion guards in your code. So perhaps that could be causing things to go a little screwy with gcc.

Also between lines 45 and 46 of the bool Deque<T>::dequeueBack(T &itemRef) function in "Deque.h" you need to add a 'return true', otherwise you'll get some errors or warnings from the compiler (in both *nix and microsoft environments.)

I've not got a *nix box in front of me at the moment, so I can't test this, but replacing all instances of '#pragma once' with traditional (gcc and MS compatible) inclusion guards and then adding the 'return true' to "Deque.h" would at least be a step in the right direction, if not the complete solution to your problem!

JasonHippy 739 Practically a Master Poster

Seeing as I'm paying for 2Meg broadband, I think I'm being ripped off!

494kbps down
227 kbps up

Pretty slow!

JasonHippy 739 Practically a Master Poster

No worries, glad to help!

So, problem solved??
Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Being a filthy, foul, potty mouthed pirate, my life was rated Arrrrrrrrrrrrr!
Heh heh....Sorry, R!
I agree with the previous posters. That was a bit of a crap quiz!

JasonHippy 739 Practically a Master Poster

Here's your original project back, I've included my edits in there.

See attached .zip.

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

Ah...Of course!

The parameter to your copy constructor should be const..
e.g.

BaseEnt(const BaseEnt &other);

Also you need to alter the signatures of GetName, GetHashCode and GetID so they are const.

So your baseent.h needs to look like this:

#pragma once

#include <vector>
#include <string>

#define MAX_ENTITIES 500

class BaseEnt{
	int id;
	std::string hashcode;
	std::string name;
public:
	BaseEnt();
	BaseEnt(std::string name);
	BaseEnt(const BaseEnt& other);
	~BaseEnt();

	int GetID() const;
	static int GetCount();
	std::string GetHashCode() const;
	std::string GetName() const;
};

namespace
{
	// The statics only need to be declared here in the header.
	static std::vector<BaseEnt> entities(MAX_ENTITIES);
	static int count=0;
}
// allow modules outside of baseent.cpp to be able to access the list of entities...
static std::vector<BaseEnt>& GetEntities(){return entities;}

BaseEnt FindClass_FromName  (std::string classname);
BaseEnt FindClass_FromHash  (std::string classhash);
BaseEnt FindClass_FromID    (int classid);
BaseEnt FindClass_FromCount (int classcount);

And baseent.cpp like so:

#include <iostream>
#include <string>
#include <vector>
#include "baseent.h"
#include "common_func.h"


BaseEnt::BaseEnt()
:id(count), name("unassigned"), hashcode(HashCode())
{
	name += hashcode;
	entities[id] = *this;
	count++;
}

BaseEnt::BaseEnt(std::string classname)
:id(count), name(classname), hashcode(HashCode())
{
	entities[id] = *this;
	count++;
}

BaseEnt::BaseEnt(const BaseEnt& other)
:id(other.GetID()), name(other.GetName()), hashcode(other.GetHashCode())
{
	entities[id] = *this;
	count++;
}

BaseEnt::~BaseEnt()
{
	count--;
}

std::string BaseEnt::GetName() const
{ return name; }
int BaseEnt::GetCount()
{ return count; }
std::string BaseEnt::GetHashCode() const
{ return hashcode; }
int BaseEnt::GetID() const
{ return id; }



BaseEnt FindClass_FromCount(int classcount)
{
	for(int i = 0; i < MAX_ENTITIES; ++i)
		if(entities[i].GetCount() == classcount)
			return entities[i];
	return 0;
}

BaseEnt FindClass_FromHash(std::string classhash)
{
	for(int i = 0; i < …
JasonHippy 739 Practically a Master Poster

I haven't got VS2008, so I can't load the original project. However, I've bunged the files into a VS2003 project and attempted to compile.

I can see the errors you're getting and I've noticed that if I comment out the copy constructor, those wierd errors are not thrown. So there is something about your copy constructor that the compiler doesn't like.

Offhand I'm still not sure exactly what the problem is though!

Obviously, because you've got that static counter that gets altered every time a new BaseEnt is created or destroyed, you need a custom copy constructor...So sticking with the default copy constructor is out of the question.

hmmm....More digging is in order...

BTW: Alongside commenting out the copy constructor, I've made the following edits to baseent.h:

#pragma once

#include <vector>
#include <string>

#define MAX_ENTITIES 500

class BaseEnt{
	int id;
	std::string hashcode;
	std::string name;
public:
	BaseEnt();
	BaseEnt(std::string name);
	//BaseEnt(BaseEnt &other);
	~BaseEnt();

	int GetID();
	int GetCount();
	std::string GetHashCode();
	std::string GetName();
};

namespace // contents are local/private to this module
{
	// The statics only need to be declared here in the header.
	static std::vector<BaseEnt> entities(MAX_ENTITIES);
	static int count=0;
}
// allow modules outside of baseent.cpp to be able to access the list of entities...
static std::vector<BaseEnt>& GetEntities(){return entities;}

BaseEnt FindClass_FromName  (std::string classname);
BaseEnt FindClass_FromHash  (std::string classhash);
BaseEnt FindClass_FromID    (int classid);
BaseEnt FindClass_FromCount (int classcount);

and baseent.cpp:

#include <iostream>
#include <string>
#include <vector>
#include "baseent.h"
#include "common_func.h"


BaseEnt::BaseEnt()
:id(count), name("unassigned"), hashcode(HashCode())
{
	name += hashcode; …
JasonHippy 739 Practically a Master Poster

OK, so looking at your original post again, you said that clicking on the error brought you to this line of code: extern std::vector<BaseEnt> entities; This code looks like it's from another file which you haven't posted any other code for (apart from the above line).

Looking at the errors I'm thinking that where your extern is declared, perhaps the compiler is trying to copy the original 'entities' variable and the STL code is for some reason having difficulty finding an appropriate copy constructor for the vector of BaseEnts...

So looking at the line of code that produces the error, you've got 'entities' declared as an extern, meaning that the variable is declared externally (obvioulsy in BaseEnt.cpp).

Now looking at the declaration of 'entities' in BaseEnt.cpp, one thing immediately strikes me...If you are using this variable externally in other .cpp files/classes, shouldn't it be static? I wonder if that might be causing the errors you're seeing. As 'entities' is not static in BaseEnt.cpp, who's to say that its even in scope when the extern is declared in your other .cpp file? Perhaps this is causing the STL code to trip up!

So making 'entities' static in BaseEnt.cpp might be worth a trying for starters.

I'd also consider perhaps making it static and putting it into an unnamed namespace in BaseEnt.cpp (making it private to the BaseEnt module) and then creating a static accessor function in BaseEnt which can return a pointer or reference to 'entities' …

JasonHippy 739 Practically a Master Poster

Hey Tom.
Looking at the error messages and the fact that some of them are referring to a vector and then looking at line 3 of your final block of code:

std::vector<BaseEnt> entities(;

Note: You haven't closed the brackets ')' !!

I'm beginning to wonder if the compiler is getting a bit confused and is thinking that the code after the opening bracket are arguments to the constructor for the vector of BaseEnt's...Perhaps throwing the errors you're seeing....

What happens after you close the brackets and then try to recompile??

std::vector<BaseEnt> entities();

Give that a shot and see what happens!

Cheers for now,
Jas.

JasonHippy 739 Practically a Master Poster

I appreciate your quick response!

I haven't worked with vectors yet, but I see a little better now how to pass by reference.

So I'm going to need variables in main() that will get their values changed by the functions? I'm having difficulty understanding the difference between a global variable and what ever the variable is called in main() that changes.

How do I initialize variables in a function, then pass the values to values in main? don't I have to initialize variables in main for them to even compile?

OK well, to clear things up we'll take a quick look at how different parameter passing methods affect the way that parameters to functions are handled inside functions.

There are three main ways of passing parameters to functions.
1. Passing by value
2. Passing by reference
3. Passing a pointer

Here's a demonstration of passing by value:

#include<iostream>

void somefunc(int foo);

int main()
{
        int foo=4;
        somefunc(foo);
        cout << foo; // will ouput 4!
}

void somefunc(int foo)
{
        foo *= 2;
}

In the above code, somefunction takes an int as a parameter. The int parameter is passed by value. When passing by value the function creates a copy of the value passed into it. So in main the value of foo is passed into the function somefunc. Inside somefunc a copy of foo is created. Any changes made to the copy of foo inside somefunction are not reflected in the foo in …

kadji.kahn commented: Very helpful, and detailed +1