StuXYZ 731 Practically a Master Poster

well that sort of works..

(a) you still have a junk code calculating the number of days.

(b) you have functions that return values BUT don't your compiler should tell you about that. -- NEVER allow warnings to go through.

(c) Think about what happens if day==31 in putEntry.

(d) you are forgetting in several places that C++ arrays count from zero and not 1.

StuXYZ 731 Practically a Master Poster

oK... were to start....

(a) daysInMonth should be a simple function

static int Days[]={31,28,31,etc};
if (logMonth==2)
    { 
         //process leap year (carefully)
     }
else
   return Days[logMonth];
}

This code is much better written as a static function that takes a number. You will need it when you write dayInWeek but not for the month that you are in.


(b) Your error in put entry is that you check the day against the logMonth (ie the 13th is never going to work!). And just in case you set a local variable called day =1 first [was that a debug line??]

(c) The constructor : No tests what if I accidently call it with Logbook A(0,0); .
then obviously you get MAXDay and promptly don't use it. But the function doesn't need to use MAXDay. Since your array is ALWAYS 31 entrys so just use:

for(int i=0;i<31;i++)
    entry[day]=0;

Finally, return exits the function, so there is no need for a break afterwards. [Actually the is no need for the horrific case statement... ].

StuXYZ 731 Practically a Master Poster

Nor sure what you are trying to do here.

I would like to see logbook.h and logbook.cpp please.

StuXYZ 731 Practically a Master Poster

This is not much better.

(a) size++; (Line 22) I think that should be arraySize.

(b) You have a for loop with i, (line 17) . Then you do not allow the loop to continue but have a while(i<arraySize) . Oh yes and the for loop is actually i<=arraySize because of the indirection of setting len=arraySize.
Then just incase this isn't a winner for the obstaficated c++ contest, you have another while further down using the same variable .

This is 100% a mess.

Then you have a loop in a loop using the same index variable.

Summary:

(A) Bin this code -- This will save you time.
(B) Do the job in stages:
(i) Find the first savings which has a null accountNumber.
call that variable Index.

(ii) Then have two pieces of code

If (Index<arraySize)
          {
              copy new stuff in to place. 
          }
      if (index==arraySize)
         {
             increase arraySize by 10
             copy new stuff into place
         }

Looking at the above you can easily see that it should be

If (Index==arraySize)
           {
               increase arraySize by 10
           }
       copy new stuff into place

Job done, time for something else. [Writing your unit test]

StuXYZ 731 Practically a Master Poster

Ok without a lot more of this program I am guessing. BUT it is obvious that many things need to be fixed.

(a) The start? const int len=arraySize; you don't change arraySize until the last line ? so why len?

(b) The first while loop [CHECK for i>=number of savings]:
Try:

while(i<numberofSavings &&  savings[i] &&
         !savings[i].accountNumber)
{ 
      i++;
}

The next if (savings[i].accountNubmer==NULL) well it can't possibly be true in your code.

Then is gets REALLY scary:
You delete ALL savings and then create saving +10 .... (this isn't a copy) and then you assume that everything is ok
Then we see that you allocated temp REGARDLESS of what you thought you were doing, and you are hoping that constructor populated everything perfectly???

Finally, you input data and return data WHY?

Summary:

This is such a mess. You should post the whole project. BUT before you do you should format it differently. It should have each { and } on a new line. It should be space indented so you can see your loops.

You should look at breaking things into smaller functions. E.g. Adding an extra 10 accounts. Do this with a function, then the coping etc. can be done away from the other logic and then you might be able to follow your own code.

It is simple you HAVE to simplify your code so you can easily read it thought and know how the variables …

StuXYZ 731 Practically a Master Poster

In comment about your ACTUAL code.

The error is that you have a continue .
This is not what you want since it continues the loop. It does not reset i. You can see this error with a simple cout on the start of your for loop.

I am not going to say you need a break . (although it works, the code structure is awful.) Why even test numbers like 1. Surely any integer has this as a factor.

StuXYZ 731 Practically a Master Poster

This is a problem that requires thought NOT code.

The answer can be easily found on a piece of paper.

So without giving you the whole solution try thinking about this
Obviously 20! (20x19x...1) is a solution but it is not the minimum.

Now you have two types of numbers primes and non-primes:
2,3,5,7,11,13,17,19 : so your solution has to be a factor of
2x3x5x7x11x13x17x19 == 9699690
[Sorry I actually did that on calculator ;) ]

Then it is easy, all you have to do is find all the prime factors of each other number and find the lowest common addition to the prime list that you already have. Then you have your answer.

E.g. for the above consider 6: it is 2x3 so no addition is required.
But 4: is 2x2 so you have to add at lease one 2.

That is a much much better way of solving the problem, particularly because if I was setting the problem, next week I would add that I want the lowest 1-1000, and brute force methods will die.

Salem commented: Excellent, think the problem first, then write code. +27
StuXYZ 731 Practically a Master Poster

Before you get strangled with compiler errors. Please note that in c++
you write public: Then all things below are public (until either the end of the class or one of private: or protected: The reason I am flagging THIS error up, is that the compilation error you generate is likely to be completely indecyferable.

Complete diversion : [P.I.M.P please ignore (sorry)].
VernonDozier said:

There's no function in C++ that can retrieve the length of an array.

Now I would have agreed for the last 20 years BUT last week I saw this:

template<typename T, int size>
int getArrayLength(T(&)[size]){ return size; }

And that works in a simpler context (ie the given situation)

#include <iostream>

template<int size>
int
func(int (&X)[size])
{
  std::cout<<"X == "<<size<<std::endl;
 return 0;
}

int main()
{
  int A[50];
  int B[80];

  func(A);
  func(B);
  return 0;
}
VernonDozier commented: Nice. +11
StuXYZ 731 Practically a Master Poster

Just to be clear.

The problem is that you have allocated an array as user users[2]; . This gives you two user objects. They can be referenced as users[0] and users[1].


When you start doing users[2].logonName; etc, you
have corrupted the memory of your program and what happens next is pure chance and unpredictable. (and normally bad!).

So increase your array to size 3, and then fix the loop which needs to be for(i=0;i<3;i++) Don't feel too bad, as always, when anyone starts on classes they seem to overlook the simple stuff for a while. [It will come back to you in a bit.]

StuXYZ 731 Practically a Master Poster

Sorry I am going to be harsh. This is by far and away the worst prime factor sort that I have EVER EVER seen. Do not code until you have considered the maths.

Consider a number[TEX] N[/TEX]. (which is a positive integer)
First if a number has a prime factor, [TEX]p[/TEX], e.g 2,3 etc. The biggest prime factor is either [TEX]p[/TEX] or the biggest prime factor of [TEX]N/p[/TEX].

That allows you to reduce the number you are searching for by a long way.

Second, from the first rule you can deduce that the largest value you need to test is the [TEX]\sqrt{N}[/TEX] [rounded down to the nearest integer]
Pseudo Proof :
consider two prime factors: [TEX]a,b[/TEX] such that [TEX]ab=N[/TEX], then if [TEX]a=N^{1/2}+x[/TEX] and [TEX]b=N^{1/2}+y[/TEX] obviously [TEX]ab=N+xy+(x+y)N^{1/2}[/TEX].

[Note [TEX]x^{1/2}[/TEX] is the same as[TEX] sqrt{x}[/TEX] ]

So why does your problem return a blank screen --- because it is using billions and billions of CPU cycles and expanding a vector to an unbelievable size.

Finally?: Your code doesn't even give the right answer! Try 121 as the input value.

Finding prime factors from large numbers is an extremely difficult thing to do. (and extremely CPU + memory intensive). But there is a lot of literature on this, and a lot of improvements over Eratosthene's sieve method, but to make it an O(N) worst is impressive :)

How to proceed

So I would start with a simple routine to check if …

StuXYZ 731 Practically a Master Poster

If you are using linux, there are a few tricks to make life MUCH better.
I am assuming that by debugging you mean the error messages that gcc/g++ give you when you compile your code. [Not, how to debug you code are runtime, which gcc facilitates but doesn't do]

Ok first there are IDE's for linux (e.g. eclipse). I don't use them since I hate being confined to so small a number of views of the code and I like emacs/gcc.

Second: Learn to use make. A simple make file for each project is a massive saving in time. [and vim/emacs both support building from it, if that is how you want to work]

Now if you are using gcc native. There are some ways to make life better.

(a) Know that you can pipe the errors to a file e.g. g++ file.cpp 2> error.log . The advantage of this is that you can the edit the file and I use vim to edit the error file.
[along with a :set nowrap] and everything looks lots better.

(b) gcc gives LOTS of warnings. Be prepared and build up you code in small fragments and REMOVE all the warnings by improving your code.

(c) Use g++ -g and don't do -O or -O2 since you want to debug it easily, while developing.

(d) ddd is your debugging friend!! Compile with g++ -g and no optimization and the ddd program.

Finally, the …

StuXYZ 731 Practically a Master Poster

First off the error that you have made is that in C++

void print(char*);
void print();  

are two different functions/methods.

Thus you HAVE NOT defined a print() method in class IVM.
You defined some weird function called void print(IVP* iv) and that is not void print()

That is why the program does not call it.

Second, the huge number of errors/warning from using istream, cstdlib and cstring etc in the include are because the compiler is trying to help you write better code.

I strongly suggest that you get a copy of gcc. Code your assignments in that and it will help a lot more. (gcc is free). If you are sticking with windows there are several other free compilers as well, but gcc is so universal and very very picky about writing to the standard. (something that university professors can get very mark happy about!)

StuXYZ 731 Practically a Master Poster

The short answer is yes, BUT it does not do the obvious thing.

Let me explain a bit. It is the same as:
(assumes that matrix[][] is of type char.)

bool X=  (matrix[1][1]==matrix[2][2]);

bool Ans  = (matrix[0][0] == static_cast<char>(X))

Note that it is VERY unlikely that is what you really want since bool
will only give you char(0) or char(1).

Also that you are using matrix[][] is completely unimportant e.g.

int a(5),b(5),c(5);
if (a==b==c)
  {
     std::cout<<"This is never written"<<std::endl;
  }
else
   {
      std::cout<<"Surprised??"<<std::endl;
   }

hope that helps.

p.s. you need to do (matrix[0][0]==matrix[1][1]) && (matrix[1][1]==matrix[2][2])

StuXYZ 731 Practically a Master Poster

The question should be asked "how do I delete a pointer if I allocate the memory using xxxx?"

Let us review:

if you write

double* Ptr=new double[50];    // Allocate space for 50 double s
// ... other code
delete [] Ptr;                             // Delete the pointer to 50 doubles
// CARE:
// Ptr is still pointing to a value

but if you write

double* Ptr=new double;        // allocate 1 double 
//.... other code
delete Ptr;                       

Note as pointed out, delete removes the memory for the pointer BUT does not change the value of the pointer variable. e.g.

double *Ptr=new double[50];
std::cout<<"Ptr memory location == "<<reinterpret_cast<long int>(Ptr)<<std::endl; 
delete [] Ptr;
std::cout<<"Ptr memory location == "<<reinterpret_cast<long int>(Ptr)<<std::endl; 
// 
// THIS CAUSES A RUNTIME ERROR:
// DO NOT DELETE TWICE
//
delete [] Ptr; 

Note in the above example , if you set Ptr=0; after the first delete then all is well.

Finally::

double X[50];        
//.... code
// NO DELETE Required:
// THIS CAUSES A RUNTIME ERROR:
delete [] X;    

If the pointer is from an object that is not allocated via a new then don't delete it.

Note: that if you are using malloc etc, then you must use free. If you are not using malloc, then don't start using it.

Hope this helps

StuXYZ 731 Practically a Master Poster

As cikara pointed out, you are incorrectly using trys!=b and that is going to get you into a mess.

I would (a) suggest that you use a count of the zeros to decide if you have succeeded. (b) Have a look at your algorithm. (c) check the rules of since you are not checking that the square (3x3) only contains 9 unique digits.

The algorithm is going to get stuck. THEN you have no way to back track ( ie suppose that you have put 1 in game[0][0] but that turns out to be incorrect then how do you replace that with a 2 if putting a 1 does not violate the problem.).

In your code, game is ok to be global, but solver should work with its own copy. Then the starting values can be set to allow iteration progression.

However, the algorithm is awful, especially as you scale to larger sudoku (4x4, 5x5 ..., 3x3x3 etc). Even for 3x3 you have on average about [TEX]10^{30}[/TEX] options (based on typically, 55 open positions)

However, if you try to keep a possible list for each square, then a series of simple rules will fill a large amount of the grid in (or reduce the search list. (and the determination of ring depends will allow you to prove that the problem has multiple solutions.)

StuXYZ 731 Practically a Master Poster

If it is to much to change in my code then that is all you had to say.

Well it works like this, you have posted two functions that DONT work.
I wrote a little bit about why they don't work and you don't want to try to fix them. Then you want the community to tell you how to change them to what you want!!

So it is either (a) a learning project (b) homework , (c) real production code. If it is (c) then you would be using std::list (or at least saying why you can't). If it is (a) then start by fixing what you have posted.

So don't just demand the answer you want. Enter a discussion.

StuXYZ 731 Practically a Master Poster

It is simple you fix deleteFront and insertBack, because neither work.

This looks like homework -- therefore show some effort.

If it not homework, show some pride in your work. Fix the first problems first.

StuXYZ 731 Practically a Master Poster

What you have clearly doesn't work:

Consider insertBack, you do not set first. It can be anything!

IF you had set first then conversion is easy.

newNode->link=first;

Now consider deleteFront, I do not understand what you are doing checking first->info (and what would happen if first was zero!)

So try testing these two functions with a range of input.

StuXYZ 731 Practically a Master Poster

Try replacing the whole while loop stuff with this.

std::cout<<std::string((people+500)/1000,'*')<<std::endl;

If you don't want to use the string constructor then try...

for(int i=(people+500)/1000;i;i--)
   std::cout<<'*';
std::cout<<std::endl;
StuXYZ 731 Practically a Master Poster

Hi,

I am amazed at this code. The normal way to do a trapezium integral is simply to loop over the value like this

const int N(500);
const double startTime(0.0);
const double endTime(100.0);
double area(func(startTime)+func(endTime));
area/=2.0;
for(int i=1;i<N-1;i++) 
   {
      area+=func(i);
  }
area*=(endTime-startTime)/N;

What you are doing creating 100000 objects to do that is absolutely beyond me. However, I think you have the code mostly right ! So well done

BUT the problem is MATHEMATICALLY very ill-conditioned. I suspect that is why it was set. I guess that you will use Simpson next and then runge-kutta on the underlying differential equation. (I will comment just about ANY monotonically decreasing/increasing function is ill-conditioned under this integral method.

If you REALLY want to get the right answer with a trapiz. method then do the problem in log coordinates.

StuXYZ 731 Practically a Master Poster

Hi,

You have made several errors (a) mis-understanding of C++ [these are critical since they affect all further programming in the language]
(b) logic errors. They only effect this program.


I think that you have mis-understood the class encapsulation rules.
Private data is available to all members of the class as both the current and other versions of the class.

Let me give an example:

class A
{
    private:
        int x;
    public:
      void func();
      void f2(const A&);
}
       
void 
A::func()
{
    x++;   // acceptable
}

void 
A::f2(const A& Other)
{
    x+=Other.x;      // Also acceptable
}

Notice that func is able to just change x. Also f2 is able to access Other's version of x as well as its own. Note also by making Other const I have forbidden that Other's x is changed. If I make a mistake in the code logic and do change Other's x (or anything else in x) then the compiler will tell me. Important. compiler errors are many times easier to find than runtime errors. Almost anything that moves errors from runtime to compile time is worth doing.

That means that you don't need all the getTdollar etc with outputData() since it is a class member method.

If your class has a constructor / copy-constructor / assignment operators, you should nearly alway initialize everything. [Unless an expert (and even then most of the time) you should always define these three methods + the destructor explicitly

StuXYZ 731 Practically a Master Poster

Given the HUGE size increase, if you have a calculation that can be done out to a large number, then the iterator route is best, (calculating the next on the fly). However, I haven't needed that by n=4 the quantum mech path calculation is (a) decaying to nothing (b) getting very inaccurate [numerically] (c) getting to take a very very long time.

mrboolf commented: This is giving me much to think to - iterators and such :-) +2
StuXYZ 731 Practically a Master Poster

If that solves your problem, please mark the thread as solved.
(You can always start a new one with a different problem).

StuXYZ 731 Practically a Master Poster

First of all thanks for posting something that isn't a homework question :) [or at least doesn't read like one].

Secondly, I assume that you are writing this to do something. So I am guessing to how you want to use them.

Next: I have used partitions in real code, but I never store them, I use them as iterators. I want a begin() and end(), so that I can do the correct path integral in a loop. Yes your code can do that but it is a bit of a drag to store all that memory. Having said that it isn't a big problem

The most important thing is to sort the list. In a normal QM path integral 1+1+1+1 is normally much bigger than 4. So it is possible to calculate the first few in the set and ignore the remaining ones. The ordering is normally problem specific.

Algorithmically, you can do you construction loop by recursion, or just by counting up. It is easier (I think). That way the previous solutions on the vector can all be used, and just copied in.

Finally, return const references from both getPartition and getPartitions..

Overall thanks for the post.

mrboolf commented: thank you for the interesting reply +2
StuXYZ 731 Practically a Master Poster

Just in case you forgot. You can easily append to the end of the file.
Use

std::string input="Hello at the end";
std::ofstream File("file1.txt",std::ios::app);
File<<input<<<std::endl;        // This is written at the end of the file.

Obviously, if you don't want to change the original, you need to make a copy, but often a simple system command will do that for you, without having to worry about writing a loop/reading/writing etc.

StuXYZ 731 Practically a Master Poster

I am glad that solved the problem.

The best thing to do is mark this thread as solved.
Then ask the question again in a new thread.

(I am really not the person to answer your questions, at lunch at work, my group were trying to figure out how many hours we had used each OS, I got to 50 for all MS systems in total, compared to 15000 for Linux. I have had a cushy life :) )

StuXYZ 731 Practically a Master Poster

Whoa, I would NEVER have thought of that string issue if you wouldn't have told me. I'll look into it but just a few questions while we're at it:
1) How do you explain that it works when I first write to the file and then read,

Well that is not an easy question since my version of your code doesn't. BUT if when you read/write, you look like you may have caused string to reserve the same length. It is also possible that
you are writing junk to a piece of unused memory. (not that string is referenced counted, so you should check that changing the original AFTER your read/write doesn't change the string on the later -- that would be another unexpected corruption.

Note you may get different behaviour dependent on you compiler optimization flags, your compiler choice and which implementation of the STL you choose.

2) With the "<<" thingies, you're suggesting I turn my binary file into a text file, don't you?

Yes. But how can you tell the difference (AFTER it has been written)
of a binary file with the characters
"abc" or a text file with the characters "abc". :)


3) Can't the string issue be solved by using char arrays of predetermined size?

Yes -- Careful because that sort of thing is very easy to get wrong in different ways.

StuXYZ 731 Practically a Master Poster

Sorry but I am going to disagree with Freaky_Chris for the second time in two days! I hope he realizes the I agree with him most of the time :)

Anyway, you MAJOR sin is to think that reading into a class which may or may-not allocate memory will work. Let us take an example:

class X
{
   int * array;
};

Now the size of class is undetermined. You don't know when the size will change. So NEVER do a binary read into a class/struct unless you have absolute certainty about the size. Practically that means no pointers to memory, no STL object (e.g. vector or string) since these reserve an unknown amount of memory, no classes with static objects.

In your case you read from User. And look it has std::string. And wait, std::string often uses reference counting and static members, so that you corrupt memory is no surprise.

Your best bet is to read each item one by one. e.g.

void write(std::ostream& OutS)  const
{
    OutS<<username<<std::endl;
    OutS<<password<<std::endl;
    OutS<<verified<<std::endl;
    return;
}

void
User::read(std::istream& Input)
{
    Input.getline(username,'\n');
    Input.getline(password,'\n');
    Input>>isVerified;
    return;
}

That will actually give you LESS bytes of output than a binary dump.

p.s. you had better add some error checking to the read method, and you could implement some operator<< and operator>> methods if you like.

[Note: To the experts: I know you can do the binary writing and reading but that is because you know exactly how to do …

Freaky_Chris commented: Hehe, agree with me when you have a reason. I' self taught so i lack alot of knowledge and college takes alot of time of my ability o read around. I always appreciate extra material to read +1
StuXYZ 731 Practically a Master Poster

This is easy.... Count
If you get below zero then you have failed,
and if you get not-zero at the end you have failed.
You might want to check scope bridges. I.e.
icode}[/icode] which I would pass as fail.
but that is easy to modify the code below to include.

Example of pseudo code for JUST ( and ).

string A = "(expession) with ) ( ";
int b(0);
for(int i=0;i<A.length();i++)
 {
   if (A[i]=='(') b++;
   if (A[i]==')') 
     {
       b--;
       if (b<0) failed();
     }
} 

if (b!=0) failed();
success();

Additionally, I am sorry BUT you cannot use boolean values as suggested by freaky_chris since
the expression ((x+y)) would fail. And that is not acceptable.

StuXYZ 731 Practically a Master Poster

You haven't posted enough to figure thst out certainly.
My guess is that x and/or bestP are double/float etc and you are committing the cardinal sin of using == with floating point numbers.

I am guessing that x is very very close to bestP but that one is held in a register. The printf causes x to be dropped out of the register onto a memory location (i.e from 80 bit to 64 bit) and then == returns true. It should also work with any other complex command.

If this is the case, please read my post in http://www.daniweb.com/forums/thread160698.html

If not, please post a little more code including the definitions of the variables. Maybe make a short test case.

p.s. Please use preview post to get the [ code ] sections correct.

StuXYZ 731 Practically a Master Poster

I am going to comment on the maths/computing interface.

You have two problems here, first is that although mathematically correct, the formula [tex]\frac{-b\pm\sqrt{b^2 - 4ac}}{ 2a}[/tex] is is awful as a computational base, since, as you partially discovered, if a or c are very small you get junk.

So you set
q=-\frac{1}{2}(b+sgn(b)\sqrt{b^2-4ac} )
and the roots are q/a and c/q. (sgn is the 1 if b>0 and -1 if b<0)

Note: additionally you need to check the condition that
b^2-4ac\ge0 or do the calculation in the complex plane.

Additionally, this still holds if the coefficients (a,b,c) are themselves complex or quaternions. (the condition is different).

There are many numerical discussions in scientific literature on
(a) approximating this (to speed up the calc at the cost of accuracy)

(b) the issue of machine accuracy. google scholar is helpful, but a membership of the ACM digital library is also going to help [and it is expensive].

(c) Numerical Recipes for X, have a discussion in chapter 5. http://www.nrbook.com/a/bookcpdf.php Note: I have given the link to the free to download pdf of the 2nd edition. You pay money for the third editions and NEVER put NR code in production code, as it is rarely robust.

p.s. I am not a proper mathematician. So if you talk to a REAL mathematician he/she will complain at my imprecision.

vmanes commented: Good comments on the math +7
StuXYZ 731 Practically a Master Poster

Remember the K&R masterpiece:

while (*dest++ = *src++);

Unforgettable Algol 68's genes are still alive in C and C++ ;)...

can I just add, you need to remember to add a *dest=0; line after the while. You will need something similar in any of the other posts.

StuXYZ 731 Practically a Master Poster

Actually, it is simply to use

gcc -shared -o libmyshared.so file1.o file2.o

Have a look at the gcc manual. http://gcc.gnu.org/onlinedocs/.

The only thing that you will need to be a little careful of is were to put it so that it is system wide. That is normally defined as directories in /etc/ld.so.conf. That means if you put you lib in /usr/local/lib it normally works.

However, you can get round that by using it as

gcc -Wl,-rpath,/home/serk/yourlocallibpath -o finishedProg file.o libmyshared.so

There are a few more options in the manual but really that covers just about everything. (obviously, you put that in your Makefile appropiately)

StuXYZ 731 Practically a Master Poster

Yes it did. There were are number of horrible errors associated with
gcc-3.4 series on reverse iterators. You have to use == and !( iter == v.rbegin()) or as you say write you own.

I am sorry but I pity you having to write for 3.4. (My problem is I have users who want to use 4.4 alpha.... ;-)

StuXYZ 731 Practically a Master Poster

To open an output stream it is output.open("ParkingCharges.txt",ios::out); NOT: ofstream.output("Parking Charges.txt", ios::out); Because you are using a class name not an instance/object (ofstream is not an object) and you are using output which is not in the class or the public base classes.

StuXYZ 731 Practically a Master Poster

You error is the fundamental language mistake. It is not possible
to declare any new variable or object in the scope of the switch statement that has outside scope. ifstream input("help.txt"); is not allowed.
Additionally, you have already declared input at the top
[4 lines below main()].

If you want to try this

switch(option) 
{
  case 'h':
   input.open("help.txt");
  break;
  .....
}

Further, you don't actually use input and output, but define a NEW
instance of output in the function CarParking.

perhaps you wanted this

int CarParking(std::ostream& output,const int min)
{
     int total = 0, time = 0, fees = 0;
      time = (min/60);
     // rest of your code
}
StuXYZ 731 Practically a Master Poster

I have seen this problem before. I would advise
(a) Never round up/down until the end.
(b) It is tempting to count the large number significant bits in the input data e.g. if the user enters 3.45 lb + 12.3 oz. And then say round to 3 sig.fig. but you will annoy more users than not.
(c) It is better to round to +/- 2 + log_e(items_added) of the lowest significant number. E.g in the example above the SLN is 0.1 oz so you get a +/-0.25 oz.
spread into the base units.

In short that worked for me, but it depends on your user base.

If this is a scientific user base, you are less and less able to round numbers and you head from biology to physics.

StuXYZ 731 Practically a Master Poster

You have missed that you could have 2 aces e.g.
AAK45 would be 21 but you will not score it as such.

So ADD 10 if you have an ace. Since you can't have two. as AA+ 20 == 22.
e.g. lines 42-46 become

if ((dHand < 12) && (Ace == true))
{
 dHand += 10;
}

Notice you have also made the beginners error of writing ace=true which is always true and sets ace to true. But any modern compiler gives warnings about that.

StuXYZ 731 Practically a Master Poster

Hi

Ok in no particular order a few problems with this code + the fix for your compile problem. (I hope)

the do { } while loop in main is a double test, try something like

int flag;
do
  {
     singleChar=getChar();
     flag=validateChar(singleChar);
     if (flag)
        std::cout<<"valid"<<std::endl;
      else
         std::cout<<"no valid"<<std::endl;
} while (flag);

That way you don't call validateChar twice on the same code.

displayCharIndex is wrong because the ine
char* strchr .... is a function declaration (function returning char*)
you want something like....

int 
displayCharIndex(char strArray[], int size, char ch)
{
char* strchr; 
//search code 
//make strchr point to the first instance of ch in strArray
// ...
return strchr-strArray;

I am guessing this is an assignment so I haven't written the search code for you. If you make an attempt and get stuck, please re-post.
Additionally, since you are using the stdio calls (strlen etc). Don't name your variables similar names e.g. strchr. You will get into a mess later.

StuXYZ 731 Practically a Master Poster

The mistake is that you are using integers (the set 0,1,2,3 and -1 etc)
to represent floating point number. int a=2*1.2; gives sets a to 2.

write

double Meters;
double Yards;

instead of the two int declarations.

StuXYZ 731 Practically a Master Poster

The reason is that anArray is local to the scope of the function. So by the time that you use it with the ptr is it out of scope. Old compilers, use to allow this (without warnings), and no end of mayhem followed.

To get round this, you can (a) declare it on the heap int* anArray=new int[5]; .. populate ...

or (b) declare it static static int* anArray={1,2,3,4,5}; If you use option (a), you are responsible to deleting the memory!

StuXYZ 731 Practically a Master Poster

First off. What do you want to do about multiple edges? The problem you have is that link-lists are very specialized graphs, in which they connected linearly as A-B-C-D.

So do define topographic graph in the sense of your diagram, you are going to have to add some additional linkage to the program.
There are many ways of doing this:

Maybe define an edge + a vertex. Not that each edge can only
connect two vertex.

struct Node;         // Pre-declare

struct Edge
{
   int cost;
   Node* A;
   Node* B;
};

struct Node
{
   int data;
   std::vector<Edge*> ConnectionList;   // this can be an array etc
};

Note that each vertex (node) can connect to any other node in multiple ways e.g. a simple two node graph A B , could have two routes from A-B and even a route A-A. hence Node A would have 3 edges. (and Node B would have 2).

Once you have separated Node from Edge, most things are relatively straightforward. However, the next "interesting" problem will come when you need to define a Loop class, (one which records a cyclic loop). or a Route class, but you don't need it for this problem.

So now make those two structures proper classes, add copy/assignment etc.
Produce a container for all of them and be come up with a simple plan to do memory management. That should be all you need for a while.

Finally, I use integer cost …

StuXYZ 731 Practically a Master Poster

First off I am going to deal with the minor errors. The the major problem.

Number of minor errors:

(A) Only constructors take the ":" assignment . Error in line 18 in
destructor. It should read ~BinaryNode() {delete left; delete right;} (B) Maybe delete line Compare compare . Use it as a direct functor if (node == NULL || Compare()(key, node->key)) Major:

This code is unlikely to behave as expected. If you put say in keys
3,5,1 then when it inserts a new node, it does no re-attach the
existing items to the tree. (as well as not working, this is a memory leak)

Additionally, I feel that you are being let down by your compiler. It is not reporting useful error messages. It really helps to have another compiler sometime (e.g. gcc) [likewise if you use gcc most of the time, something like Portland or IBM etc].

Finally, it is strange to include the .cpp file in the .h file. That is because you want to use the header without including all the code. If you need a template instance, then sometimes it needs to be done
but not all the time.

I look forward to the next installment :)

StuXYZ 731 Practically a Master Poster

Ok the problem, that doesn't actually occur until you try to create a version of the BinaryNode (from BinarySearchTree) is that you have written:

BinaryNode(Key k, T i) : data(i), Key(k)

Note that Key is now a type [From Line 6].

You need to use key. Or please use a different word. (I like "key" for
your key name that is fine but the word "Key" as the template typename does not convey the sense of type)

Additionally, please use the references uniformly, for example if you have a key (say a string) by not having BinaryNode take a reference,
there is additional coping. Although, some compilers will help you on the optimization pass.

Hope this helps.

StuXYZ 731 Practically a Master Poster

My guess is that you have a template that cannot be expressed as a float/double type
e.g.

template<typename T>
void printout(const T& Obj)
{
  print("%2f",Obj);
}

and then

class SomethingComplex
{
....
};
SomethingComplex A;
printout(A);

There are many possible solutions but why not use the printf() in the class write function
and access by an operator<< overload. e.g.

class S
{
  ...
  public:
     void write(std::ostream&) const;  
};

ostream& operator<<(std::ostream& OX, const S& A)
{
   A.write(OX);
   return OX;
}

void
S::write(std::ostream OX) const
{
  char ss[6];
   sprintf(ss,"%2f %2f\n",internalA,internalB);
   OX<<ss;
}

ALTERNATIVE:

you might want to use the boost library (format).
e.g.

std::cout<<boost::format("%1$-2f") % Number;

BUT this doesn't get round the requirement that Number and the format type need to agree.