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