Murtan 317 Practically a Master Poster

You want to put the date and time in the title of the window that pops up, or do you want the name of the directory to contain the date and/or time?

For getting the date/time into a string, you might look at strftime() and you should probably also consider calling mkdir() instead of system("mkdir ...") to create the directory.

Salem commented: Nice +19
Murtan 317 Practically a Master Poster

You're iterating too far.

The element indexed by cnt wasn't fully read.

On Line 25 the loop limit should be i < cnt not i <= cnt

Murtan 317 Practically a Master Poster

You need to seek before you read (saw you have that), but you need to seek to the same location before writing (by default, the act of reading moved the file pointer).

//Insde main:
     else if(choice==2)
     {
       cout<<"\nEnter the sl.no. of the book :";
       cin>>bno;
       int loc=(bno-1)*(sizeof(books));
       // seek for reading
       file.seekg(loc);
       file.read((char*)&B,sizeof(books));
       B.update();
       // seek for writing
       file.seekp(loc); 
       file.write((char*)&B,sizeof(books));
       file.seekp(0,ios::end);
     }
abhaymv commented: Thank you again! +1
Murtan 317 Practically a Master Poster

I think your problem is that you don't read the records from the file when you're making changes to them.

For example if the first thing I did after starting the program was to check-out or check-in a book, I select menu choice 2 and this is the code:

else if(choice==2)
     {
       cout<<"\nEnter the sl.no. of the book :";
       cin>>bno;
       int loc=(bno-1)*(sizeof(books));
       file.seekp(loc);
       B.update();
       file.write((char*)&B,sizeof(B));
       file.seekp(0,ios::end);
     }

You seek to the position but don't read the data.
Then you update whatever the B class had in memory.
Then you write out the contents of the B class.

It would probably be obvious if the check-out/check-in process displayed the name of book and the number of copies you thought it had.

Unless you're running with a debugger (and you'd probably not be asking the same questions if you were) add more printing (at least for debugging, you can comment it out later if you don't want it in the final version). Knowing what your program is doing and understanding why it is doing what it is are the keys to making it all work.

Here's a personal style comment, feel free to ignore it:
Which is easier to read?

cout<<"\n1.Add new book.\n2.Issue/return book.\n3.Edit book info.\n4.Show book info.\n5.Add new user.\n6.Update user info.\n7.View user info.\n8.Delete data base .\n9.Aboout\n10.quit.\nEnter your choice: ";

or (this works because the compiler merges adjacent strings)

cout<<"\n"
          "1.Add new book.\n"
          "2.Issue/return book.\n"
          "3.Edit book info.\n"
          "4.Show book info.\n"
          "5.Add …
Murtan 317 Practically a Master Poster

The compiler requires that the 'interface' function1() declared in the base class have a concrete argument list.

What kind of abstraction do you think it needs?

Could that abstraction be implemented with another base class?

If the function call is abstract, how will the caller know what to pass the abstraction?

Murtan 317 Practically a Master Poster

Templates require the users to see all of the member functions. You can't have the methods 'hidden' in a c++ file.

If the code creating the instance of the template doesn't "see" the method, the method does not get implemented.

This is due to the way templates are implemented. They are not implemented as generic methods that work for any type, they are implemented as specific methods for the types identified.

If you had a tree with two different argument types (say IntBinaryTree<foo> and IntBinaryTree<goo>) there must be an insert node defined for each...(IntBinaryTree<foo>::insertNode() and IntBinaryTree<goo>::insertNode()) they will not find or use a 'generic' insertNode().

(It is possible to have the template derive from an actual base class if there are methods that can actually operate without the type, and the implementation for the base class methods would be 'hidden' in a cpp file and linked to the code.

Murtan 317 Practically a Master Poster

My original thought was that you would track the current editor as a frmEditor in your code. Upon further thought and contemplation (see reading the manual) I have revised my opinion.

We can use this.ActiveMdiChild but it is of type Form and not the class we want (frmEditor). We need to 'cast' it to our type so we can call our method (as our method is not defined in the Form class).

We can use the c# 'as' to make the conversion for us, without throwing an exception if the cast fails. (If the cast fails, as returns null.)

frmEditor currentEditor = this.ActiveMdiChild as frmEditor;
if (currentEditor != null)
    currentEditor.method(arguments);
Murtan 317 Practically a Master Poster

That makes sense I suppose, but if it is a MDI container, and there is an active child window, when the user clicks the menu on the main form, does that make the child window lose focus? If it loses focus would using this.ActiveMdiChild work?

Also...I'm a little lost about why you would call a function in that way, it seems like you are doing it backwards... like...

frmEditor is the location of the method I want to run, so in order to run a method there I need to call the method by making a new object and then assigning that object a value that is never used anywhere? That's what it looks like you are doing. frmEditor currentEditor = this.activeEditor. so what is currentEditor and activeEditor? other than within the if statement where you reference currentEditor.method(), why would you bother doing frmEditor currentEditor = this.activeEditor. ...couldn't you just say frmEditor.method()...it seems to me that it would be the same? Maybe I'm thinking of it wrong?

Clicking on the menu or toolbar in an MDI parent does not change the MDIChild focus. (Note that it is tracking an MDI focus, the menu or tool bar might have the event focus, but the MDI child focus was not changed.)

You have to have an instance to call a method. If you have 3 editors open, which one would you mean if you say frmEditor.method() ?

The frmEditor currentEditor = this.activeEditor; makes a copy of a reference that the …

Murtan 317 Practically a Master Poster

Lets try to describe the problem better...

Is the problem:
a) search the directory for a file name
b) search a specific file for string data
c) search all of the files in a directory for string data
d) search all of the files in a directory tree for string data
e) something else

Be clear and concise in your problem description.

We also tend to be a lot more helpful if you show that you're trying to do this yourself. Include a list of the steps you would follow if you were trying to solve the problem manually. We can discuss the list and help you write the code to make the steps happen.

Murtan 317 Practically a Master Poster

I'm presuming that x is the number of array entries you filled. A more descriptive name would be more appropriate.

line 15 in your code would be executed for every pass of the loop.

If the first one doesn't match, then line 15 assumes you can't find it and terminates the loop.

You need to move the line 15 test outside the for loop and remove the break.

You will also need to set look to false before the for loop starts.

Murtan 317 Practically a Master Poster

You generally call methods on an object instance. (This is why I was talking about 'keeping' a reference to the child windows you created and 'knowing' which child was the current one.) You would ask the current form to save.

// If you setup using a framework and setup your main window to support MDI
// you might be able to use this.ActiveMdiChild
// but it will be of type Form and not frmEditor
frmEditor currentEditor = this.activeEditor.
if (currentEditor != null)
    currentEditor.Method(arguments)
Murtan 317 Practically a Master Poster

For a multiple form interface, you will need to keep a list of all of the open forms and keep the list current when forms are closed or opened. You will also need a method to reference the 'current form', the one the user is currently interacting with.

When the user clicks save, you should save the data from the current form. (You might consider adding a 'save all' button that would iterate all of the forms saving each of them.) It also might be beneficial to have a 'dirty' flag that would let you know if the form had any changes to save. You could set the dirty flag any time a change is made to the text field.

Based on your described implementation, I think I would be tempted put the serialization in the child form. The main form would only call a method to tell the child it was time to save and the child would take care of getting it done.

Murtan 317 Practically a Master Poster

This code will not compile because I am trying to assign a myTemplateClass <int> pointer or myTemplateClass <char> pointer to myTemplateClass pointer.


Can we declare a pointer array that can hold myTemplateClass pointer of any type?

Using void pointer will not help much, since it needs a lot of type casting that may introduce bugs. Also it calls for type tracking of each object, which is nasty.

The only way I can think of to be able to store untyped or generic pointer to either template instance would be to have the template class inherit from a base class the defines all of the operations that you might need to perform on the instances of the template. You could then declare your array to be an array of pointers to the base class and any template instance would satisfy the pointer.

Another approach I can think of is to declare two arrays of pointers, one to myTemplateClass<int> and one to myTemplateClass<char> , both of size 10. If you pre-initialized both arrays to NULL values, you could look at either one first, if the value is NULL, the data item is of the other type.

A third approach might be to have a structure that contains the data type and a union of pointers to the possible implementations. You could then have an array of those.

Both of the last two cases require you to keep re-evaluating the type and handling the pointers in a type-safe …

Murtan 317 Practically a Master Poster

Now we're getting into scope a bit (and its a big topic) but class-level variables only exist once, regardless of the number of instances of the class.

Based on your example, where you want something to persist, it could be a regular member of a class instance and the form could keep that instance around as long as the form was open, it wouldn't have to be a class-level data item. Depending on the data you want to persist, the form could just have the data instead of another class (forms are usually classes too) if that would be more convenient.

class1 and class2 normally don't have any idea that the other class exists unless they need to use the class for something. That is normally a GOOD thing. It encourages and promotes modularity in the code.

If it was necessary, class2 could access the string inside class1 if the string was declared as a public member of the class. Then class2 could reference the string via something like class1::class1string . I would personally however tend to discourage it. If you have an example where you think it might be appropriate, describe it and we'll evaluate whether or not that's a valid application and discuss alternatives.

Murtan 317 Practically a Master Poster

Yes that would be a valid example.

Another example would be a 'person' class. Each person has attributes: name, address, phone number, birthday, ...

But any two instances of 'person' are different.

Murtan 317 Practically a Master Poster

I apparently wrote this while Ryshad was replying. He covers most of it in a more elegant fashion, but I'll post it anyway.

Local variables work like you mentioned your i did in VBA. If you declare it in a function, it goes out of scope when the function ends and is no longer available.

In C# as long as someone still has a reference to an object (or list or other collection of objects) the objects continue to persist.

If the form references a car, the form can continue to refer to that same car as long as the form exists. (Even if the user is not interacting with the form at the time.)

Regarding your form and button question, as long as the two components reference i in the same way relative to the form, they would be working with the same value.

Yes, the process of extracting data from an object in memory and writing it to an output (sometimes a file, but could be something else) is what serialization is.

The "objects can hold multiple values" is somewhat incorrect. I think what you're confused with is that there may be more than one instance of an object.

If Car is a class, then Car myCar = new Car(); declares an instance of a car that I called "myCar". I could then additionally declare Car yourCar = new Car(); . Than made 2 different, but similar 'cars'. Each car has …

Murtan 317 Practically a Master Poster

Well, ignoring that your input doesn't do much to protect the user from themselves (for example, enter "fred" when it asks for the account number and see what happens)...

Do you know in advance (or can you ask) how many they want to enter?

If you could, you could wrap the input and output in a loop. Something like the following where numberToEnter is an integer that was set prior to the loop:

BankAccount aBank(0, 0, 0);
		for (int acctindex = 0; acctindex < numberToEnter; acctindex++)
		{
			cin>>aBank;
			cout<< aBank;
			aBank.interest();
		}

That re-uses the aBank instance so at the end, you still only have one instance, but you have filled it and output from it multiple times.

Murtan 317 Practically a Master Poster

You're having an entity vs value comparison issue:

a = [[1,2],[2,0]]
b = [2,0]
aa = a[1]
# at this point, b = [2,0] and aa = [2,0]
# but aa == b returns False

# aa[0] == b[0] returns True
# aa[1] == b[1] returns True

Python is comparing the list entities and not the list values.

sneekula commented: Very good point! +6
Murtan 317 Practically a Master Poster

I was working on revamping the code...most of it would need changes to work with the classes.

Murtan 317 Practically a Master Poster

Ok, I'm going to post this...I've started it several times and then you post a significant rewrite of your code and to help you I have to toss this stuff out.

You can use the idea and expand on it, or ignore it, it's up to you, but I think that this would make your code easier to work on and more maintainable.

I think you should be doing more with classes, but I surely did not mean for you to turn your whole game into one large class. You are also using class variables in many instances where they are not needed. If you only use a variable within a single function, it does not need to be a member of a class.

Here's a start at classes to support stores and items:

class NQShopItem(object):
    """
    This class holds the information common to all shop items
    """
    def __init__(self, name, price, reqLevel, reqRank):
        self.name = name
        self.price = price
        self.reqLevel = reqLevel
        self.reqRank = reqRank
    
    def shopline(self, idx):
        return "   %2d - %-32s $%5d" % (idx, self.name, self.price)
    
class NQWeapon(NQShopItem):
    """ 
    This is a class that represents weapons in NorbertQuest
    """
    def __init__(self, name, price, reqLevel, reqRank, damage):
        #NQShopItem.__init__(self, name, price, reqLevel, reqRank)
        super(NQWeapon, self).__init__(name, price, reqLevel, reqRank)
        self.damage = damage

NQWeaponList = [
    #         Name              Cost Lvl rank  Dam
    NQWeapon("Hands",              0,  1,   0,   0),
    NQWeapon("Steel Knuckles",    50,  1,   0,  35),
    NQWeapon("Knife",             75,  2,   0,  55),
    NQWeapon("Sword",            300,  3,   0,  90),
    NQWeapon("Gun",              800,  4,   0, …
Murtan 317 Practically a Master Poster

If you're having a problem with part of the code, please be specific as to what the problem is. What did you see? What did you expect to see?

If it is a compile problem, include the full text of the compiler error if possible.

I saw something interesting in your new banking code, you ask for the amount to deposit/withdraw using raw_input. This alone is not a problem but it does mean that the amount is a string and not a number. You will need to convert it to a number before you attempt to compare against the balance or the cash-on-hand.

Murtan 317 Practically a Master Poster

Just as a side note, you could make the game a lot easier (potentially faster too) if you would let the user select things by number.

For example when selecting "battle" "shop" or "exit" if the menu was:

Available options:
    1 - Battle
    2 - Shop
    3 - Exit
What would you like to do?

The user could enter '1', '2' or '3' instead of having to type out the whole word.

The same could be applied to the battle sequence.

But even better, might be some way to more automate the battle...something like 'auto-attack' that would keep attacking until the monster was dead or you died. (Maybe you could work out a way for the player to make some input into the battle while it was in-progress?)

In my sample play, I don't believe I have ever been killed by a monster. Especially not after I upgraded my weapons.

Oh...another usability item...when you open the shop, it would be nice to tell them which weapon they're using and how much money they have so they would know what they could afford and which weapons would be an upgrade to the weapon they have.

Murtan 317 Practically a Master Poster

I would reset the player and monster health at the start of the battle.

The weapons would make a good class, the weapon has a name, a cost and an amount of damage. Then you could make a list of weapons that could be iterated for display at the shop. When the player buys a weapon, you could update their 'current' weapon and then use the 'current' weapon when calculating damage during the battle.

The following is some sample code of how the shop might work after you create the weapon class and a list of them. The sample code does not attempt to format the list in a 'pretty' form or to validate the user input, both would be beneficial updates.

for idx in range(len(weaponlist)):
    print idx + 1, weaponlist[idx].description, weaponlist[idx].cost
z = input("Which weapon do you want?")
if money > weaponlist[z].cost:
    playerweapon = weaponlist[z]
    print "You have bought", playerweapon.description
else:
    print "You can't afford the", weaponlist[z].description

The functions that display the health (of the player and the enemy) also calculate the damage applied and as such are poorly named. (The function name does not reflect what it does.) I would tend to separate them into a couple of functions, one to display the health and another to calculate the damage for an attack and apply it.

In the current program it is possible that the player might not have enough money to even buy the lowest weapon. If they can't buy a weapon, how …

Murtan 317 Practically a Master Poster

If you don't intend to use any of the predefined C++ data types in your implementation, what do you propose to use?

A 6000 byte long number could be implemented, I would probably use an array with 6000 elements, but that still uses base C++ data types.

(Ignoring the fact that arbitrary precision math class is probably already available.)

I'd recommend getting over the "I don't want to use the ___, how do I do ___" mentality and focus on the objective of what you want to be done. Use the tools that are available.

If you don't have an objective that has been assigned, from school or work, then develop your own objective and assign it to yourself. This question appears to be argumentative on the surface. If you have a real-world situation that would make this line of inquiry make sense, feel free to present it.

BevoX commented: Thank you for your answer it reflects you also like to think out of the box. :) +1
Salem commented: Good +29
Murtan 317 Practically a Master Poster

@starzstar

I think the module you're looking for it getopt

It is designed to parse command line arguments and handles the type you indicated.

@keerthihm

You should probably have started your own thread and not replied to this one.

You seem to be asking about testing a binary tree.
Which are you wanting?

  • help testing a binary tree algorithm
  • help calculating the number of comparisons that must be made when searching a binary tree
slate commented: Clears things up. +1
Murtan 317 Practically a Master Poster

Whether or not the source is available for a given library is up to the developer of the library.

If the source files are not included, you can't step into them. (Unless you like to read disassembly.)

If the library is only released as a dll, the same applies.

If you are having problems with a library that was released without source, you are generally not supposed to attempt to debug it.

If you are having a problem with such a library, you confirm that you are using the documented interface and then 'prove' that the function you call does not behave as documented. You then 'present' the evidence to the library supplier and they will usually fix the problem and release an updated library.

Murtan 317 Practically a Master Poster

I've always thought that the 'snake' collision detection just looked at the next square the snakes head was going to be put. If there's something in the square, its a collision. If its food, the snake eats it and that's a good thing. If it's wall or part of either snake, it's a bad thing.

As long as you apply the same rule to both snakes, it should be able to detect collision with objects for either snake.

Salem commented: Seems like a plan to me +27
Murtan 317 Practically a Master Poster

You already have a 'global' (ok so it is local to the class, but all of the class methods can see it) data area defined. See this section under private in your class:

private:
	double average;
	string courseName [4];
	char  gradeLetter [4];
	int gradePoint [4];

The only reason you aren't sharing the data is because you hide it by re-declaring the same variables inside your functions:

Here

void displayMessage ()
	{
		char  gradeLetter [4] = {};
		string courseName [4] = {""};

and here

double getAverage ()
	{
		int gradePoint [4] = {};
		char  gradeLetter [4] = {};
		double average = 0.0;

You can just comment out (or delete) the declarations under each function and they will use the class data, sharing it between them.

I noticed why you aren't having to enter four grades for each class, it is the break inside the for (y ... loop.

I might ask why you even have that loop anyway. Why not just do something like the following? (I have commented out your code where it is not needed or where I have modified it.)

void displayMessage ()
	{
		//char  gradeLetter [4] = {};
		//string courseName [4] = {""};

		for ( int x = 0; x < 4; x++ )
		{
			cout<< "Please enter name of course:";
			getline(cin, courseName [x]);

			//for ( int y = 0; y < 4; y++ )
			//{
			cout<< "Enter grade recieved:";
			//cin>> gradeLetter [y];
			cin>> gradeLetter [x];
			//	break;
			//}
			cin.ignore …
VernonDozier commented: Good advice. +11
Murtan 317 Practically a Master Poster

Please don't answer each post since your last with the same string, we all have to read through all of them.

I can't imagine any phone system where you can pre-order sequential 7 digit phone numbers, but ignoring that for now...

Why does the 7 digit phone number have to be a string?

Or if it does, why can't you convert it from a string to a number, add one and convert it back?

If you're REALLY desperate, you could convert the last character of the phone number to a number and add 1. If the number is now 10, put a '0' down for the last digit and 'carry' the one to the next-to-the last character. (At least that's how I learned to do manual addition when I was in school.)

Salem commented: Very good, nice simple "string" addition, just like how it's done on paper. +27
Murtan 317 Practically a Master Poster

On line 2, r is coming from the values in the dictionary, not the keys.
So you can't use it as a key on line 8, you can't index a dictionary by the definition.

You could either test to see if the answer is a key and if it is, if the value matches the definition you have.

Alternatively (and probably better) iterate the keys on line 2 and then don't print the key, but print what you lookup from the dictionary using the key on line 6. Then you can just compare the answer with the key value.

SoulMazer commented: A big help. Followed through. +1
Murtan 317 Practically a Master Poster

Once you 'know' what class it actually is, you can cast the pointer...

if (typeid(*pacct) == typeid(SavingsAccount)) {
    SavingsAccount * pSave = (SavingsAccount *)pacct;
    // or more explicitly
    SavingsAccount * pSave = reinterpret_cast<SavingsAccount *>(pacct);
    // then
    pSave->credit(pSave->CalculateInterest());
}

But a better implementation really would be to define all of the functionality that you might ever expect from an account in the base class with virtual methods so you don't have to jump through the 'what type is it' and 'make it one of what it is' hoops.

You could either implement something like virtual int ProcessMonthEnd() which in the base Account class might do nothing. Then in the derived classes it is overridden to do what that account type needed (for example posting interest to a SavingsAccount).

for each (Account * pacct in accounts)
{
    pacct->ProcessMonthEnd();
}

Or you might decide that any account might earn interest. So you implement virtual bool EarnsInterest(); and virtual double CalculateInterest(); in Account. The base Account implementation would return false and 0, but the methods could be overridden (say in SavingsAccount) to return true and the current interest calculation.

for each (Account * pacct in accounts)
{
    if (pacct->EarnsInterest()) {
        pacct->credit(pacct->CalculateInterest());
    }
}

As long as the methods are declared as part of Account, you can call them without having to cast anything.

(My personal preference would be to avoid the RTTI and casting, but it is YOUR code.)

We are definitely headed into the 'implementation specific' details. …

Murtan 317 Practically a Master Poster

Note 1: Indenting is your friend, make much better use of him.

Note 2: if you're in your main() and you return, your program is done

I'm not sure what's up with the two-level menu, where you only handle one case from the first menu and two cases from the second menu. (Please at least put place-holders in that say "Not Implemented" so you can see your program structure.

Note 3: functions are your friends too, it is generally bad form to have all of your code in main().

Making the user type the eof character on the keyboard to indicate 'done' is also bad form. A more common implementation would be to quit if the user entered a blank line, or entered "quit" or "done" or some other specified input rather than looking for eof().

Back to your original question, if you want the menu to loop, you have to put it in a loop. Your code as written would need some work, but you could put a do { before you display the menu and put a } while (choice != 6); after all of the menu processing.

Or pre-initialize choice to a zero and make the loop while (choice != 6) { and end with }

Salem commented: Say "yes" to indentation! +27
Murtan 317 Practically a Master Poster

I suspect your problem with multiple inheritance is actually a multiple-include problem.

If you put Freaky_Chris's example in one file, you have no problem.

If you put all 3 classes into separate files that don't include each other, no problem. If the file for b includes a and the file for c includes a and your main includes both b and c, your main sees the following unless you protect from it:

class a{};
class b: public a{};
class a{};
class c: public a{};

The compiler then complains about a being defined twice.

The code sample you posted is similar to the portable way to prevent multiple inclusion. In each of your include files that need to be protected, add the 'wrapper'. The wrapper changes depending on the name of the include file. So in Account.hpp it would be:

#ifndef Account.hpp
#define Account.hpp
// The rest of what you currently have in Account.hpp goes here
#endif

This causes the contents of the file to be parsed only once. The second time the compiler 'sees' the file the symbol is defined and it skips to the endif.

For SavingsAccount.hpp the wrapper would look like:

#ifndef SavingsAccount.hpp
#define SavingsAccount.hpp
// The rest of what you currently have in SavingsAccount.hpp goes here
#endif

In some older code I used to work on, we used _ characters on the symbols, so the symbol for Fruit.hpp would be something like _Fruit_hpp_

The actual symbol you use in …

Murtan 317 Practically a Master Poster

I suggested that children should never be a friend of their parent.

Parents should define anything the children should have access to in the protected: section.

I was also arguing that in this case, the balance should remain private and the child classes would use debit() and credit() to update the balance.

Murtan 317 Practically a Master Poster

And even that looks like something the instructor gave you. With the "do not modify" and "add code here" comments:

Salem commented: Points for due diligence - I just saw the mess and moved on +27
Murtan 317 Practically a Master Poster

I think your only option is to change the color of the characters.

Take a look at this snippet

If you set your 'default' color to grey or light grey, white characters will appear 'brighter'.

ddanbe commented: Nice suggestion! +4
Murtan 317 Practically a Master Poster

So 'list' is an index into the virtual heap, and each entry in the virtual heap is a structure that has an elem (the value at that node) and a next (the index in the virtual heap for the entry with the next higher elem).

When there are no entries in the list, the list * l passed to this function will point to -1 (indicating end of list).

So when you add 5, 2, 1 we should end up with:

l = 2
vh->h[0].elem = 5       vh->h[0].next = -1
vh->h[1].elem = 2       vh->h[1].next = 0
vh->h[2].elem = 1       vh->h[2].next = 1

When you add 5, 3, 6 you should get:

l=1
vh->h[0].elem = 5       vh->h[0].next = 2
vh->h[1].elem = 3       vh->h[1].next = 0
vh->h[2].elem = 6       vh->h[2].next = -1

But you appear to be getting:

l=2
vh->h[0].elem = 5       vh->h[0].next = ?
vh->h[1].elem = 3       vh->h[1].next = ?
vh->h[2].elem = 6       vh->h[2].next = -1

The next debugging step would normally be to add some code to dump the entire virtual heap just to confirm what you have is what you think you have. However, I think I see your problem. int * p starts out pointing to the passed in value list * l .

The for loop on line 10 is supposed to 'walk through' the list until it finds where the new value is supposed to go, then it is supposed to update the next value of the record that should …

Whilliam commented: smart post. +1
Murtan 317 Practically a Master Poster

We are not, nor have we ever been a 'here is your completed assignment because you asked for it' source of information. Our basic premise is to help you fill the 'gaps' in your knowledge. We help you to solve your own problems. Post some code for how you think it should work, identify where you're having trouble and we will pitch in with suggestions.

Salem commented: Well said!!! +26
Murtan 317 Practically a Master Poster

To do more with the color, you're probably going to want to look at the component parts of the tuple.

For example, the following would count any pixel with more green than red and more green than blue:

for pixel in list(img_I):
    red, green, blue = pixel
    if green > red and green > blue:
        green_I += 1

This counts pixels with any green:

for pixel in list(img_I):
    red, green, blue = pixel
    if green > 0:
        green_I += 1

Some of the 'problem' values for the first case:

  • 254,255,254 - Almost pure white
  • 254,255,0 - Almost pure yellow

Some of the 'problem' values for the second case:

  • 0,1,255 - Almost pure blue
  • 255,1,255 - Almost pure purple

If you wanted to get pixels that were 'mostly' green, I would probably use something like the first case, but make sure the color parts are more than just 1 apart. How far apart would be part of the definition of 'mostly'. And if you want to make sure it was more of a 'pure' green than say a yellow-green or blue-green, you might want to include something about the ratio of blue to red. (In a 'true' green, there are equal parts of red and blue.)

Murtan 317 Practically a Master Poster

Not to be picky, but #define NUMBERS is a pre-processor directive and doesn't get scope.

(But it should have been outside the function anyway.)

Aia commented: Correct +12
Murtan 317 Practically a Master Poster

Ok this will be a bit of code, but bear with me. The concepts came from the tutorial link from the earlier post and some test code I wrote to make sure I understood how it works. (I've never used a map before today, but I've used similar objects from other languages.)

#include <map>
#include <string>
#include <utility>

void testcode()
{
    struct Person
    {
        int age;
    };

    map<string, Person> mapOfPerson;
    // or if you prefer you can use a typedef
    typedef map<string, Person> PersonMap;
    PersonMap People;

    // To add someone to the collection, you can do:
    People["Jim"].age = 19;

    // behind the scenes, when you referenced "Jim" the map found that he didn't exist
    // and then added him with a default value

    // This just adds Carl, but doesn't set his age
    People["Carl"];

    // You could also add someone "the hard way"
    Person sample;
    sample.age = 22;
    People["Bob"] = sample;

    // Once someone has been added, you can do things like:
    cout << "Bob is " << People["Bob"].age << endl;
    // Bob is 22

    // To determine who is in the list (or to find if someone exists) requires an iterator
    PersonMap::iterator finder;

    finder = People.find("Carl");
    // ok this part is a little more involved...but you can do things like:
    cout << finder->first << " is " << finder->second.age << endl;
    // Carl is 0

    // The previous example presumed that we would find what we searched for
    
    // We can find someone who doesn't exist,
    finder = …
NewtoC++ commented: Exactly what I was looking for +1
Murtan 317 Practically a Master Poster

ok, I did the default constructor and called resize(). The assert is gone and the program runs.

I also did a little more playing, I added a third player 'Bob' who is also a CPU (not that it really matters right now).

Here's the output from my last run:

### HAND 1 ###
CPU's hand: Nine of Hearts, Ten of Spades, Jack of Hearts, Queen of Spades, King of Spades
Bob's hand: Ace of Spades, Eight of Spades, Jack of Diamonds, Jack of Spades, Queen of Hearts
Ludovico's hand: Eight of Hearts, Nine of Diamonds, Ten of Clubs, Jack of Clubs, Queen of Clubs

CPU has Straight, King high
Bob has One Pair, Jack
Ludovico has Straight, Queen high

### HAND 2 ###
Bob's hand: Ace of Hearts, Eight of Diamonds, Ten of Diamonds, Jack of Clubs, King of Clubs
Ludovico's hand: Eight of Clubs, Nine of Spades, Queen of Diamonds, Queen of Spades, King of Diamonds
CPU's hand: Ace of Diamonds, Ace of Clubs, Nine of Diamonds, Ten of Hearts, King of Hearts

Bob has High Card, Ace
Ludovico has One Pair, Queen
CPU has One Pair, Ace

### HAND 3 ###
Ludovico's hand: Ace of Hearts, Ace of Diamonds, Eight of Diamonds, Jack of Diamonds, Queen of Diamonds
CPU's hand: Nine of Diamonds, Ten of Spades, Jack of Spades, King of Diamonds, King of Clubs
Bob's hand: Eight of Hearts, Ten of Diamonds, Jack of Hearts, Jack of Clubs, King of Hearts

Ludovico has One …
mrboolf commented: Wow, what a post! Thank you! Now that Christmas is gone I think I'm going to partially rewrite this project following some of your advices before going on. Thanks again for your time :-) +2
Murtan 317 Practically a Master Poster

I took the zip file and made a MS project around it.

I had to add #include <algorithm> to hand.cpp but other than that it compiled.

I then uncommented your troublesome line:

void pokerGame::showdown() {
    for(unsigned int i = 0; i < m_players.size(); ++i) {
        if(m_players[i].getHand().getSize()!=0) {
            std::cout << m_players[i].getName() << "'s hand: ";
            std::cout << m_players[i].getHand() << std::endl;
        }
    }
    return;
}
void pokerGame::showdown() {
    for(unsigned int i = 0; i < m_players.size(); ++i) {
        if(m_players[i].getHand().getSize()!=0) {
            std::cout << m_players[i].getName() << "'s hand: ";
            std::cout << m_players[i].getHand() << std::endl;
        }
    }
    return;
}

It runs ok, but the output is strange:

dealing to Ludovico
dealing to Cpu
dealing to Ludovico
dealing to Cpu
dealing to Ludovico
dealing to Cpu
dealing to Ludovico
dealing to Cpu
dealing to Ludovico
dealing to Cpu
Ludovico's hand: Ace of Nine, Two of Spades, Four of Five, Three of Six, Four of
 Six
Cpu's hand: Ace of Ace, Ace of Five, Two of Four, Ace of Six, Two of Seven

I think the problem is here:

void deck::build(int numPlayers) {
    m_discarded.clear();
    m_dealt.clear();
    m_deck.clear();
    if(numPlayers == 0) {
        for(int i = 1; i <= 4; ++i) {
            for(int j = 1; j <= 13; ++j) {
                // -- a card expects value , suit which is what we say we're passing
                // -- but j is 1-13 and i is 1-4
                m_deck.push_back(card((value) i, (suit) j));
            }
        }
        return;
    }
    for(int i = 1; i <= 4; ++i) {
        m_deck.push_back(card((value) 1, …
mrboolf commented: Great, you saved me from a big headache! Thanks +2
Murtan 317 Practically a Master Poster

The problem with using "A-" as a variable name is that it is illegal.

You can create a variable A_minus without any problem, but you don't want the user to be inputting your variable names anyway.

You will want to take their input as a string "A-" and use that to find the appropriate point multiplier.

This seems custom aligned for a dictionary.

gradepoints = {}
gradepoints["A"] = 4.00
gradepoints["A-"] = 3.70
# put the rest of the relationships here
# There is an easier way to initialize dictionaries, 
# feel free to find it and use it

Then you can use the user input to 'index' into the dictionary to get the point multiplier.

Try to use the idea in more of your own code and post any problems you find.

sneekula commented: Nice approach to help +6
Murtan 317 Practically a Master Poster

Please, when posting python code, use code=python tags

As I said in my previous messages, you needed to indent more lines to make them part of the loop.

house= ["computer", "laptop", "tv", "nintendo DS", "table", "Empty"]
print "items in my house are:"
print house
    
while house[5] == "Empty":
    print "Pick an item to fill in the empty space: \n1 - Lamp\n2 - bed\n3 - NDS\n\n"

    choice=raw_input("Type a number and press enter: ")
    print


    if choice =="1":
        house[5] = "lamp"
        print "Items in my house are now:"
        print house

    elif choice =="2":
        house[5] = "bed"
        print "Items in my house are now:"
        print house

    elif choice =="3":
        house[5] = "NDS"
        print "Items in my house are now: "
        print house

    else:
        print "\nYou need to pick a number from 1-3"

In python, the indenting is CRITICAL to the program structure, so much so that having two items indented at different levels is actually a compiler error: (** This code will NOT compile **)

sum = 0
for x in range(5):
    sum += x
        print x, "new sum", sum

It is actually one of the several features of python that I love. Either learn to love it, learn to live with it, or move on to another language.

Murtan 317 Practically a Master Poster

None of the characters ever "HAVE" to match anything.

The way it works is something like this:

Lets say we have a char * date that points to "01/12/2009" which is in memory as '0','1','/','1','2','/','2','0','0','9','\0' when you call strtok(date, "/") it actually returns a pointer to the first character and modifies the memory to look like this: '0','1','\0','1','2','/','2','0','0','9','\0' note that it changed the first '/' into a '\0'.

When you call strtok(NULL, "/") it remembers the last place that it changed and starts searching from there. So it steps to the next character (following the one it changed to '\0') and compares it to the delimiter '/' in this case. '1' isn't '/' so it steps again and keeps looking. '2' isn't '/' either so it steps again. The next chararcter '/' is the delimiter, so it changes it to a '\0' and returns the a pointer to the first character it started with (the '1' in this case). Now the memory looks like: '0','1','\0','1','2','\0','2','0','0','9','\0' note that the original 'date' still points to the first '0' in that memory string.

Now for the (sarcasm on) all important third call and its delimiter (sarcasm off) when you call strtok(NULL, '/') it does what it did in the last call, but it never finds the '/' so it just returns a pointer to the character following the character it last changed (the '2' in the year). The memory still looks like '0','1','\0','1','2','\0','2','0','0','9','\0' but the code knows that it …

devnar commented: Well explained. Thanks. +1
Murtan 317 Practically a Master Poster

As a note, I love using functions to help break things up. You have several things which would support that well.

1) The 'assignment' asks you to fill the board with pairs of numbers from 1-8. On line 15, you fill with a random number from 1 to 8. Where are the pairs?

2) The hints recommended a second array to indicate whether or not a specific card was hidden. That's what you should be updating.
If the two cards match, leave the cards face up, if not, turn them back face down.

You should probably be doing more input validation. (Can the player 're-pick' something where there has already been a match?)

Add a 'while there are cards to match' loop to the code.

Salem commented: Nicely put +25
Murtan 317 Practically a Master Poster

So you want the loop to keep running while the xPos is different or the yPos is different. You wrote while the xPos is different AND the yPos is different. The loop needs to run while either doesn't match.

while((board.getgXPos() != board.getXPos()) || (board.getgYPos() != board.getYPos()))
SHWOO commented: Helpful! +3
Murtan 317 Practically a Master Poster

If you're not going to use sortField, go ahead and remove it.

PS- ddanbe is right

In my sample program, the sort submenu looks like this:

sortExit = false;
                do{
                   char sortCommand;
                   cout << "1: Student ID" << endl;
                   cout << "2: Quiz 1 Grade" << endl;
                   cout << "3: Quiz 2 Grade" << endl;
                   cout << "4: Exam 1 Grade" << endl;
                   cout << "5: Exam 2 Grade" << endl;
                   cout << "6: Assignment 1 Grade" << endl;
                   cout << "7: Assignment 2 Grade" << endl;
                   cout << "8: Assignment 3 Grade" << endl;
                   cout << "9: Return to main menu" << endl;
                   cout << endl;
                   cout << "Enter field to be sorted(1-8): ";
                   cin >> sortCommand;
                   
                   switch (sortCommand){ 
                          case '1':
                               for (int ii = 0; ii < Num_Students; ii++)
                                   scores[ii] = grades[ii].ID;
                               sortList(scores, Num_Students);
                               showList(scores, Num_Students);
                               break;
                          // 
                          // Skipping cases for 2-8 here
                          // 
                          case '9':
                               sortExit = true;
                               break;
                          default:
                               cout << "Invalid Command" << endl;
                   }
                }while( !sortExit );
ddanbe commented: respect is mutually, this is a hard one +3
Murtan 317 Practically a Master Poster

I did some initial review, and I was able to load the library and call hgeCreate using ctypes:

Run this from a directory with the hge.dll in it, I was in the hge181 directory.

from ctypes import *
hge = windll.hge
hgeCreate = hge.hgeCreate
hgeCreate.restype = c_void_p

hge = hgeCreate(0x180)

But from there, it would seem ctypes does not support making calls into c++ classes, and that appears to be how you interface to the rest of hge. (hgeCreate returns a pointer to an instance of the class)

Prahaai commented: Very concise. It solves some of my problems. +4