If you were given the assignment to do it by hand, how would YOU do it?
(The manual process makes a good basis for the pseudo code for the computer.)
If you were given the assignment to do it by hand, how would YOU do it?
(The manual process makes a good basis for the pseudo code for the computer.)
Your implementation of find_text would only attempt to iterate to lower elements if the current element had no text.
Having text does not preclude having child nodes.
I rewrote your find_text as follows and I'm seeing output now:
def find_text(element):
if element.text:
yield element.text
for subelement in element:
for txt in find_text(subelement):
yield txt
When posting c++ code, please use c++ code tags
[code=c++] // Your code here
[/code]
Don't try to print answer on the 'please enter in two numbers' lines.
Someone please correct me if I made a mistake ;)
That hardly ever happens I'm sure. :)
And your description matches my empirical testing.
Q4 worked when I took out the extra space in front of line 2
Q2 is a slice construct I had not seen before. Apparently the full slice spec is [start : end : step] so [::-1] says I want the whole string stepping backwards.
You can slice any list or string...play with it, it is a fun syntax.
It can also be used to make a true copy of a list. Most list assignments do not make a copy, they copy a reference.
x = range(5)
# x contains 0,1,2,3,4
y = x
y.append(7)
# y and x both contain 0,1,2,3,4,7
# because they both refer to the same list
z = y[:]
z.append(10)
# y and x are unchanged because z doesn't refer to the same list
# z contains 0,1,2,3,4,7,10
int(rand 10) returns numbers in the range 0 to 9
int (rand 10)+1 returns numbers in the range 1 to 10
while(1) is a continuous loop...it will keep looping until you 'break' or 'last'.
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. …
Ok so we want a user registration system where we can authenticate existing users and register new users.
So when you first start the game, do you want it to prompt for login/register or do you want to just prompt for username and password and if the username is unrecognized offer to create a new account?
Is your game a console application, does it use windows, or does it play from a server?
Where do you plan to store the usernames / passwords?
How much security do you need? (Do you care if someone 'hacks' someone else's account?)
Not that it matters as mine seems to work, but I am running Vista.
In your helper function:
ostream& operator<<(ostream &output, const BSTree &other) {
output << outputHelper(&output, other.overallRoot);
return output;
}
It doesn't know what outputHelper is supposed to be.
You could attempt to call it with other.outputHelper(output, other.overallRoot);
but outputHelper is private (as I suspect overallRoot is).
I would tend to provide a public method, something like DumpInorder(ostream & output)
that would make the call to outputHelper(output, overallRoot). Then your helper function looks more like:
ostream& operator<<(ostream &output, const BSTree &other) {
other.DumpInorder(output);
return output;
}
We generally do not provide canned answers to problems.
Especially not homework problems.
We prefer to help you help yourself.
In your case, first think about the problem. Think about the steps you would follow to solve the problem by hand. Use that plan as a basic design for the program.
Then once you have some code, we're great at providing answers to problems like "The program is doing ___, I expected it to do ___"
The more specific you are about what it is doing that you don't like and what you wanted it to do, the better the answers you will get. (With good questions, the answers tend to come faster as well.)
When you go to post your c++ code, please use c++ code tags
[code=c++] // Your code here
[/code]
Unless your application could write to multiple files at once, I suspect that multiple threads won't be much help. It would be hard to get different threads to write to different parts of the same file where the parts don't even really exist yet.
Put some more thought into it and ask a more specific question.
How do you envision the program (or function) working?
What data will be provided to the program?
What data do you expect the program to output?
Does the user interact with the program?
If so, how?
What do you want the program to do?
If you can't explain what you're trying to do, we can't help, and even if you can, we want you to at least put some effort into it. We generally do not provide canned solutions here, we help you to help yourself.
The code was really hard to read...
When posting c++ code, please use c++ code tags
[code=c++] // Your code here
[/code]
You have a couple of places where your loops are wrong:
// This type is wrong, it will go one too far.
for(int j=0; j<=asize; j++)
// This type is the right way to do it.
for(int j=0; j<asize; j++)
And your 'print the contents of an array' code that you keep repeating might make another good member for your Array class.
You also write code this way quite a bit:
for(int j=0; j<a.size;j++)
*(ptr+j)=*(a.ptr+j);
Do you realize that this is functionally equivalent to the much easier to read:
for (int j = 0; j < a.size; j++) {
ptr[j] = a.ptr[j];
}
(I added the braces to the for loop because I like them)
Which of your many output functions isn't working?
Do any of them work?
What output do you have (if any)?
What do you think is wrong? (Make a guess if you need to)
My biggest complaint with Notepad++ is that I can't configure it to use tab characters for C / C++ code and spaces for Python.
I've been using the 'PyAlaMode' editor that came with one of the librarys I install (I think it comes with wxPython). It doesn't debug, but it does do syntax highlighting and has a pretty-good interactive execution window. I'm sure there are better editors out there, but its another case of how many editors do I really want to learn.
I agree with Comatose, you should probably put the part that prompts for and accepts new input inside the loop somehow. That way as the loop is run again you ask for input again.
The psuedo-code looks something like:
And as far as printing thinking of, I usually give it its own print statement right after it was generated with the word DEBUG in the output so it helps to remind me to take it out later. Something like print "DEBUG: thinkingof $thinkingof\n";
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 }
Just as a comment to the whole process...
You declared info *resident[max];
(thats an array of pointers to info) but I don't see where you ever allocated the info instances to put in the array.
(I suspect this is the root cause of your 'bugging out')
Also, Agni is right, for a linked list implementation, you commonly only keep the 'head' node pointer, you don't keep an array of pointers.
In your code, you seem to treat your collection as an array in the input function, you use linked list iteration, but swap the data instead of swapping nodes; and treat the collection as an array again for output.
In your code, an "Account *" will never be a "SavingsAccount" you are directly comparing two types. You wanted to compare an instance and a type. The following worked for me:
if (typeid(*pacct) == typeid(SavingsAccount)) {
cout << " Savings Account" << endl;
} else if (typeid(*pacct) == typeid(CheckingAccount)) {
cout << " Checking Account" << endl;
} else {
cout << " Unrecognized: " << typeid(*pacct).name() << endl;
}
An alternative implementation might be to add a virtual 'month end' method that would add interest to a savings account and charge a service charge to a checking account (unless they met the minimum balance requirements :) )
I just thought you might like another sample. Those results were from the 'problem' link you posted in message 5
That first '0' you're seeing almost looks like unresolved input.
Your menu selection only reads a character from cin, if you have to hit a return before the menu option is selected, the return may still be in the input stream when you get to calcList. Then the first read gets an empty string. If this might be the problem, you could either make sure to clear the input stream before or at the start of calcList() or you could read a line like you have in calcList() when getting the menu selection.
(I'm just slow I guess...but here it is anyway)
You can't just cast a character pointer (that is what inputVal.c_str() returns) to an int and expect to get the integer value represented by the string characters.
Sample code and output:
string foo = "124";
cout << "foo=" << foo << endl;
cout << "(int)foo.c_str()=" << (int)foo.c_str() << endl;
cout << "atoi(foo.c_str())=" << atoi(foo.c_str()) << endl;
foo=124
(int)foo.c_str()=1963856
atoi(foo.c_str())=124
I was able to get the vector to work and support the polymorphism:
vector<Account *> accounts;
accounts.push_back(new SavingsAccount(25.00, 1.00));
accounts.push_back(new CheckingAccount(80.00, 1.00));
accounts.push_back(new SavingsAccount(200.00, 1.00));
accounts.push_back(new CheckingAccount(400.00, 1.00));
for each (Account * pacct in accounts)
{
cout << "Original Balance: " << pacct->getBalance() << endl;
pacct->credit(5);
cout << "New Balance: " << pacct->getBalance() << endl;
}
The checking accounts get the fee applied to the credit.
I changed the MessageBox output to a System.Diagnostics.Debug.Print so that it wouldn't wait for me to click anything (possibly still reading in the background).
VC# Express claimed it was making a project for .Net 3.5 (I made a console application, but did not output to the console.)
This load line from the debug seems to agree with the 3.5:
GAC_MSIL\System.Core\3.5.0.0__
This is my output:
Before close: 1/19/2009 8:44:57 AM
After close: 1/19/2009 8:44:57 AM
The thread 0x1574 has exited with code 0 (0x0).
The thread 0x1908 has exited with code 0 (0x0).
The Internet will remove all of the value.
So I if I have some IP that I paid for and want to preserve the value for I should never put it on the internet at all?
Add some debug...
Does list[cnt] = (int)inputVal.c_str();
get you the numeric value you entered, or the address of the string?
When posting c++ code, please use c++ code tags
[code=c++] // Your code here
[/code]
And actually in my testing, that doesn't exit like you want it to.
It keeps looping if the character is >= ' '
OR if the count is <= SIZE
. It will not stop until both conditions are false. (PS- you want < SIZE)
If you change the "||" to "&&" you get the effect you were looking for, it will only loop as long as both conditions are satisfied.
In the testing I changed the sentence declarations to: char sentence1[SIZE];
And the function declaration to: void getinput(char *sentence)
The calls to getinput(sentence1);
and the update inside the function to sentence[k] = sentence_temp[k];
You're not terminating your output strings with a '\0', and you don't necessarily have count characters in sentence_temp.
The default constructor for Account:
Account::Account(){
customer = NULL;
strcpy(customer, ",,,;");
strcpy(accountNumber, "000000000000000");
balance = 0;
}
Is what gets called when you call new Account[arraySize]
On line 2 of the code above, you set customer to point to NULL.
Then on line 3, you attempt to strcpy into the NULL
Very bad form. You need to either declare customer like a bigger accountNumber, or you need to allocate the space you want with something like customer = new char[251];
and then make sure to delete it in the destructor. (The only problem is that the copy constructor just makes a copy of the pointer. If you decide to allocate the customer, the copy constructor will too.)
PS - if you define a copy constructor, you almost always want to define an assignment operator (operator =) to make sure the handling is the same in both cases.
Fix that and see if your problem goes away.
The counter and the array were both declared inside the sample code (calcList), they wouldn't be visible outside of it.
Please post the entire class definition for Account and for Bank.
From class Account {
to };
and the same for Bank. (For this part, I'm not really interested in member bodies, I just want a feel for what data items the class contains and the methods you have defined.)
Then I would like to see the contents of the constructors for Account and Bank.
I'm not sure why you're getting the stream errors, I'm using Visual C++ Express and I'm not seeing the compile errors.
Are you mixing options for char and wchar_t somewhere?
I was going to recommend that you only load the bitmap once, but I noticed that your code already has a comment about it:
//initialize the game...
//load bitmaps, meshes, textures, sounds, etc.
And your whole x = rand()..., y = rand()
appears to be all about picking a random location on the screen to draw at.
From what you described the desired behavior to be, you want to start your image somewhere (maybe the center?). Then you select a random direction (as dx, dy) for it to start moving. Then on each pass of the loop, you calculate the 'new position' of the image from the old by applying dx, dy and doing edge testing. (Edge testing is where you determine if the new position would cause any portion of your image to fall 'outside' the screen -- an alternative edge test if you don't mind some of your image off-screen is to edge test for the center of your image rather than the outside edges) If you have hit a screen edge, invert the direction in relation to that edge. For example if dy was <0 and we 'hit' the Y 0 edge of the screen, you make dy=-dy (which makes it positive) and re-calculate the new position. Once you're "happy" with the new position, you use BitBlt to move the image from where it was to the new position. The whole 'float about the screen' thing happens as your image 'bounces' off the edges of …
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 …
What errors are you seeing on that function, it looks like it should work.
Mine currently looks like:
void debit( double amount ) {
if (amount < 0) {
cout << "Invalid debit amount (" << amount << "), debits must be >= 0" << endl;
} else if (amount > currentBalance) {
cout << "Debit amount (" << amount << ") exceeded account balance (" << currentBalance << ")" << endl;
} else {
currentBalance -= amount;
}
}
I have not run test with the above code, but it does compile.
The last argument I was making was actually to keep the balance private and make the child classes use the member functions getBalance()
to get the balance and debit()
and credit()
to update the balance.
The print statements about bad values are probably sufficient for this level of code, but normally, you wouldn't want to print that you had a problem, but to return an indication of a problem to the caller so they could decide how to handle it. This would allow the program to customize the response to the context in which it was encountered.
So if this were for a long-term project, a better prototype might be: int debit( double amount );
Where the method would return 0 for success and a non-zero error code to indicate a problem.
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.
Bank Accounts tend to be very transactional...
Maybe it should do something like:
// Doesn't need parameters, its for 'this' savings account at the 'current' interest rate
void CalculateMonthlyInterest() {
credit( getBalance() * (InterestRate / 12) /*, "Interest Earned"*/);
};
// and account's credit would do something like:
void credit( double creditamt /*, char const * description */) {
currentBalance += creditamt;
}
PS- your last posted calculate interest method REPLACED the balance with the interest.
For your proposed initial balance handling:
Accout(double newbalance) {
if (newbalance < 0) {
cout << "Invalid opening balance specified, using zero";
newbalance = 0;
}
currentBalance = newbalance;
}
as to calling the constructor, you are calling it when your SavingsAccount constructor is called:
SavingsAccount(double initBalance, double initInterestRate):
Account(initBalance) // this is the Account constructor
{
InterestRate = initInterestRate;
};
You made SavingsAccount a friend of Account so it can modify the balance directly. What if it wasn't a friend? SavingsAccount could look at the balance with getBalance() and modify the balance through the credit and debit methods. That would give Account a lot more control of the balance to make sure that all of the 'proper' rules were followed.
currentBalance = newBalance is taken care of by calling Account(newBalance).
You could validate it in Account's constructor, but if the new balance is negative, there isn't much you can do about it.
You could exit the application or throw an exception, but if you don't handle the exception the application exits anyway, and exiting seems so unfriendly.
I'm seeing a compile error in SavingsAccount:
void CalculateInterest(Account& ac, double InterestRate) {
ac.getBalance *= InterestRate;
};
Several comments / questions:
getBalance is a method of Account (that should return a double instead of an int) but you can't update a method.
Why does CalculateInterest take an account and an interest rate as parameters? It is a member of the SavingsAccount class and has access to the parent class account and the member variable InterestRate.
And every time I've seen it used, an interest calculation has a 'period' to which it applies. Is the stored interest rate in % / year? What period is CalculateInterest() supposed to calculate for?
To use Agni's code, Account needs the Account(double newBalance)
constructor.
And even that looks like something the instructor gave you. With the "do not modify" and "add code here" comments:
I was going to give you Agni's answer (lucky I saw it when I switched to Advanced).
Also, there is no requirement that a class have only one constructor.
You could actually declare both (not that you want to in this instance):
Account(double newBalance) {
currentBalance = newBalance;
};
Account() {
currentBalance = 0;
};
(Arg! I must type slow, Dragon said this already)
Design Comment:
I'm not overly fond of adding friends to a class (I do it when I need to, but try to avoid it when possible). You should not need to make derived classes a friend of the parent. If you have things that you want derived classes to be able to see / modify, make them protected instead of private, or provide protected accessors if that works better for you.
Just wondering...Notepad and other editor like applications tend to respond to a normal 'terminate' message with a user query if their file has been modified, but don't terminate until they get an answer.
Might this be a part of your problem?
Making it images makes it harder for people to extract, so fewer people will do it, so there is some benefit.
If the goal is to reduce automated screen scraping, they have at least increased the amount of effort required.
Your last comment about intellectual property being a thing of the past, should probaly have been in some social discussion forum, but just in passing, if information has no value, why would anyone spend money to acquire it in the first place?
So line is a string and str is a C style string so you can use strtok on it.
Why not just use strcpy(str, line.c_str())
?
The only answer I come up with (and I did get the same result in my sample code) is that tabs equate to 8 characters.
You start the class at the left margin
The init function MUST be indented at least one space, but the actual count is not important, but must be the same for all future methods.
The code inside init must be indented at least one space from the init declaration, but once again the important part is that all lines in the method have the same indent.
I have a sample __init__ method that has 8 spaces for the first self.name = name and one tab for the second self.othername = name
It compiles without errors. If I add a space after the tab it complains about the indenting (like I thought it would have for the tab).
So point 1, no you're not just seeing things. Point 2 is that the default tab expansion MUST be 8 characters, otherwise we would have seen an error.
Ouch.
Why are you declaring and filling the array inside arraySearch()?
The array should either be passed in (in which case arraySearch needs more parameters) or arraySearch should reference the 'global' array. (Note that I don't like the global array answer as a matter of principle, but it would work.)
Ok, so if you have defined the array as const string secArray[10][2];
(oops, don't declare the global array const, we could declare the parameter const because we don't plan to change it, but the global one will need to be updated.)
Ok, so if you have defined the array as string secArray[10][2];
I presume that is an array of 10 users. Is secArray[ii][0] the name and secArray[ii][1] the callsign?
Why are you referencing secArray[index][2]?
Does this even compile?
if((secArray[index][2]) == (name,callSign))
Did you want to do something like:
if (secArray[index][0] == name && secArray[index][1] == callSign)
Are you really sure you want to search for both?
With the above test, if either one doesn't match, you don't find it.
Another slight modification to the 2 dimensional array would be an array of a class or struct. (I favor classes personally.)
You could do something like:
class RegisteredUser
{
public:
RegisteredUser();
RegisteredUser(string name, string callsign);
const string & getName() const;
const string & getCallsign() const;
void setName(string name);
void setCallsign(string callsign);
private:
string mName;
string mCallsign;
};
Then your array of users would be something like:
RegisteredUser secArray[10];
…Sorry for the delay, I forgot to check mail. Can you show me the declaration for the array (from main?)
Alternatively, based on the parameter declaration, you could use if(name == secArray[index][0])
in the test to see if the error will go away.
(and in reference to your post while I was posting -- this routine was never intended to compare the password, it was designed to be a NAME comparison)
If you post your code with code tags, the whitespace doesn't go away.
When posting c# code, please use c# code tags
[code=c#] // Your code here
[/code]
About the private members and array topic, I don't think I understand what you're asking.
You can do things like:
Console.WriteLine ("{0}, {1}\n\n\n", citizen[3].Name, citizen[3].Age);
Is that what you were trying to ask about?
I doubt you're supposed to search for the password to look for duplicates. The common case is where you refuse to add a user (name) because it already exists.
So a function that took the array and a name to search for that returned where the name was found (or -1 for not found) would meet your needs.
After the user enters a name / password (or maybe even just after the name) you would search for the name and only add the new name if you didn't find it.
The prototype might look something like:
// The first argument should match your array declaration
// The second argument is the number of names already in the array
// The third argument is the name to search for
// The return values should be -1 for not found and the array index for the name if found
int findName(string names[], int numNames, const string & name);
If you use an STL collection class in place of the array in the call above, the numNames shouldn't be necessary, the STL classes can tell you how many items are in the collection.
You make an effort at writing the function and we can help you if you get stuck. If you get stuck, post your code along with a problem statement (i.e. "I expected ___ but I'm getting ___")
PS- When posting c++ code, please use c++ code tags
[code=c++] // Your code here
[/code]