mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As ixmike pointed out, c is useless, and most importantly, i is not initialized (and should probably be an integer, int, and not a double).

Now, the input of p and the condition for the loop are not correct. The thing that you have to notice in this problem is that you know the value of Pi = 3.1415926535897932384626433832795 to a very good level of precision anyways. So, the important information to ask at the input is not what p should be, but to what precision you want to approximate Pi. Obviously, from the question, the level of precision required is in the number of significant digits. So, the termination condition should be when the absolute difference between your approximated Pi and the real Pi is less than required precision (±0.5, ±0.05, ±0.005, ±0.0005,...). So, you should ask for how many significant digits are needed, compute the tolerance, and use it as the termination of the loop. Now, if you were to implement this without knowing the actual value of Pi, you could terminate whenever the last change in the approximate value (i.e. the last calculated term of the equation) turns out to be less than the given tolerance.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>> The kit I have been using is called WPILib. It is extremely easy, and open-source, but is it a good, powerful library?
WPILib is certainly very easy to use... is it powerful?.. well you don't need a sledge-hammer to kill a bug. This tool will do just fine for all your purposes. If you need to simulate your robot's operation, you will have to write another library that has all the same functions as WPILib (or at least, those that you will use). Then, you implement those functions to match the behavior of your robot (to whichever degree you like). If you need some graphics and physics, look at SDL (Simple DirectMedia Layer, for simple graphics) and ODE (Open Dynamics Engine, for simple physics). You should start by just simulating without graphics and without physics, because I know that in this type of project/competition, you run out of time quickly and there is no point in trying to simulate too much. So, focus on the abstract tasks (motion planning, finite state machine, etc.) while you don't have the hardware, and worry about hardware interface and fine-tuning of performance once you have the robot at hand.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think that your cast to LPCWSTR is not correct. Read this article for a deeper explanation.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Making a Plugin System is not a trivial task... One of my friends who is very experienced tried and gave up. I made one (for windows) four years ago, and it took me about 1.5 years to get it to work properly. Now, I started a new one about 1 year ago, and it is still not finished but it is much better than my previous version. But, I have to say, it is really hard to do one if you want it to be cross-platform, cross-compiler, cross-module, and export classes and interfaces with a cross-modular RTTI system. If you require none of those things, it is quite easy.

There are plugin systems that already exist, like COM components in Windows (.ocx) or other things you have probably seen before like ActiveX. These are plugin systems with different flavors. I personally have never used them, but I'm sure it is not too difficult.

If you can reduce the purpose of you plugin to just a few functions (like parseIncomingMessage() and whatever). Then, all you really need is to define that set of standard functions, and make DLLs that implement and export those functions. This is a basic special-purpose plugin system.

So, start by looking into DLL, how to write them, export functions, load and use them from your main application. At that point, if you cannot manage to implement the functionality that you need with simple exported functions from a DLL, then you can look into COM …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I m a computer engg student & m absolutly unable 2 undrstand c++. Cn any1 sggst sme buks or ways 2 stdy C++???????
I have a book to suggest: an English dictionary! Communication is one of the most important skills in engineering.

Intrade commented: Normally I'd agree, but a lot of people here on Daniweb use English as a second language (or later than second). +0
mitrmkar commented: Yes, spell checker might be a good choice too +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Try to reinstall the build-essential package (uninstall and reinstall). That's the only suggestion I can think of... hope it helps.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This implementation is called the "dreaded diamond", this faq is very explanatory.

@arshad:>>My respect for Visual studio has increased after reading your comment
@Fbody:>>Users of VC++ are the lucky ones

MY respect for Visual studio has _decreased_ (even more) since I saw your post. I tried to find a part of the C++ standard that prescribes the behaviour of the code by the OP but to no avail. However, from me and several sources on the internet, there is a consensus that what the OP reported is what should indeed happen. If no virtual inheritance is mandated by the programmer, each inheritance path should be followed separately, leading to two instances of the base class (which can lead to ambiguous uses or references to the base class members). The fact that Visual Studio's compiler inserts a virtual inheritance scheme where none was explicitely mandated by the programmer, is a very bad thing (what other dirty hidden tricks does it do?). Although I couldn't find a passage that says that this violates the standard, I would suspect it does, and in my opinion, it does violate the strict syntax philosophy of C++. In general, the GNU GCC compiler is much more strictly compliant with the standard (i.e. if there is a difference in behavior between VS and GCC, then GCC's output can be taken as the standard expected behavior).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The main problem is that you need to get rid of header stdlib.h it corrupts the call to getline. One simple error is that your file in the search function should be of type "ifstream" not "ofstream", calling a getline on an ofstream will likely lead to an abnormal termination (usually due to two exceptions being thrown simultaneously, or worse).

With the above changes, I ran your program and it mostly works. I would also take out the line 70 (för där finns ingen tom rad melan personer i filen).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As pointed out by Fbody, your copy-constructor has not a single statement that sets the mHead and mTail pointer to anything. The fact that the copied list outputs the list without the head node, is pure luck, it should just output random shit or simply crash on a segmentation fault.

So, your deep-copy is perfectly fine, it works... except that the list is copied into the head pointer "headNode" which is thrown away after the constructors body has finished executing (which is a memory leak, btw). Now, all you need to do is replace all references to "headNode" for "this->mHead". Then, you will have to add a bit of code to keep track of mTail too.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your problem is that the constructors for TwoDimensionalShape and ThreeDimensionalShape do not carry the parameters over to the base class Shape:

//This is what you had:
        TwoDimensionalShape(double x,double y)
	{
	double Shape(double x,double y);
	}
//This is what it should be:
        TwoDimensionalShape(double x,double y) : Shape(x,y) { };
//and similarly for the ThreeDimensionalShape

What was happening is that the default constructor of Shape was called, setting each coordinate to 0.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Being a robotics engineer, I feel a bit obligated to answer... but also very happy to do so, however, your question is too vague, thus, my answer will be as well.

>>learn the SDK in C++
What SDK? What is the platform? Is it the LEGO Mindstorm? Or a micro-processor, like gumstix? Or a micro-PC?

If it is a micro-controller, then WinAVR, AVR Studio, and Arduino are the typical examples of free software on which you can program and test your programs. But these are simple I/O emulators or embedded system emulators (not a full-blown robot simulators).

The Microsoft Robotics Developer Studio is a comprehensive tool (which I am not so familiar with since it is quite new I haven't had a chance to test it out yet). It will allow you to build simulations and test your code. However, I would imagine the learning curve would be very steep for a high-school freshman.

In my experience, developing a simple simulator for a robot is far easier than writing the code to control it. And since every robot is different, custom tools are very common. And frankly, I don't know of any generic tool, but I'm sure they exist. Mostly, people build up robotics libraries (in C or C++) over the years, and good ones rarely get out of the company or research center who paid for it! CLARAty is one example of a comprehensive …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are two main reasons people ever use "char*" in C++: either they haven't learned std::string yet (meaning they are within a few weeks of having started to learn C/C++); or they are writing code that interfaces to a C library or an API written in C. If that is not your case, use std::string, it will surely be more convenient and it is usually compatible with most C-string functions too, but with stringstreams and ifstream all functionalities you might desire are already available.

The saying goes that good C++ programmers actually program in "++C" because they make use of the added features over its predecessor (C), while poor C++ programmers think they are using an improvement over C but they are actually only getting the original value. So, please try and use the best tools for your job, and, unless there are special constraints, the C++ standard libraries usually has the better tools over C libraries.

Ancient Dragon commented: good :) +34
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The point about reformatting is that you can spot mistakes in your code much more easily when the indentation is done properly. As a result, most programmers that have more than a few months of experience in coding are already fanatical about respecting format. It certainly won't magically fix any problems because the compiler ignores it, but it helps you help yourself.

As for your code (properly formatted):

int main() {

  //local constants
  const int SENTINEL = -1;
    
  //local variables
  int Base;                                //Base
  int Expo;                                //Exponent 
  int Total;                               //Total
  int Total1;                              //Calculations
    
  /**************************start main program*********************/
   
  //Get total of numbers to be inputted
   
  cout << "\n\n";
  cout << setw(50) << "--------------" << endl;
  cout << setw(50) << " Calculations " << endl;
  cout << setw(50) << "--------------" << endl;
  cout << "\n\n";
  cout << setw(55) << " Input Base (or -1 to Quit):  ";
  cin  >> Base; //notice that you set Base here, and ONLY HERE.
   
  while( Base != SENTINEL) //if you enter this loop, you will never get out because Base never changes in the loop.
  {
    if( Base <=10 && Base >=1)
    {
      cout << setw(55) << " Input Exponent:  ";
      cin  >> Expo;
    }
    else
      cout << " Base Error";
    //Isn't it strange that even with an invalid base you keep on going to the exponent?
 
    if ( Expo <=10 && Expo >=0 ) //What is the value of Expo if you entered an invalid Base?
    {
      Total1 = 1;
      for(int count = 0; count < …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

1. The function you are trying to implement is usually referred to as "concatenation" (or just "cat" for short). I'm just pointing that out to help you build a technical vocabulary for computer science.

2. There are already functions that implement this functionality. I'm sure you knew that, but just in case you didn't know. For C-style string (i.e. char*), the function is called strcat() and it does exactly what you want to do. Now, if you use C++ strings (i.e. std::string), then it is even simpler, either use the function append() or simply use the addition operator like you would with any other type.

3. As I assume you knew the above, and thus, you are doing this as a learning exercise only. It is hard to know how much help I should provide, because coming up with the logic for your algorithm is usually about 95% of the work (1% is the time to implement it and 4% is the time to fix the problems with it.. your mileage may differ). So basically, I would say the first logic step is to simply get to the end of the first string, then copy character after character from the second string to the first until you reach the end of the second string, put the null character at the end and you're done. I really cannot explain it in any simpler terms.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Normally you should be able to do it like this:

ch = init_ch;
for (int i = 0; i < 10; i++) {
  cout << "character '"<< *ch << "' is at address " << ch << endl; //you don't need the "+ i" because ch is already getting incremented.
  ch++;
}

However, since "ch" is a pointer to char, the compiler will assume it is a pointer to a string (null-terminated sequence of characters) and will try to output all the characters until the null-character '\0'. To avoid that, you need to cast the pointer to a pointer of another type, like void for example:

ch = init_ch;
for (int i = 0; i < 10; i++) {
  cout << "character '"<< *ch << "' is at address " << reinterpret_cast<void*>(ch) << endl;
  ch++;
}

that should fix it.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The variables arr and maxVarHolder are already pointers to int, using the star * will dereference those into the int variable they point to. The stars are not correct. This will work:

result = sumarr(arr, num, maxVarHolder);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Am I incrementing the address correctly or not?
No. The problem is that the expression "&ch + i" takes the address for the pointer "ch" and increments that address by "i". Now, the address of the pointer "ch" is a pointer to a pointer to a char, i.e. "char**". Since a pointer is a 32bit value (or 64bit on 64bit systems), when you increment the pointer to the pointer, it will increment it by 4 bytes.

>>Is my IDE (VC++) using 32 bit chars or is that the standard for C++?
A char is always of size 1, i.e. "sizeof(char) == 1" always, this is prescribed by the C++ standard. So even if, on some bizarre system, a char is stored with more or less than 8bits (1 byte), the "sizeof(char)" will still be 1. Say, for example, a system has chars of 16 bits, if "sizeof(int)" returns 4, it means that, on that system, an int is 64 bits long.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Forgot to mention, there is also the Boost Any library to do this kind of stuff.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This requires dynamic polymorphism (i.e. base class and some derived classes). A simple way to do it:

//a very simple base class with one virtual function (required for RTTI).
struct stack_element {
  virtual ~stack_element() { };
};

//a general class template for holding a primitive value
template <class T>
struct primitive : public stack_element {
  T value;
  primitive(const T& aValue) : value(aValue) { };
  ~primitive() { };
};

//a template specialization for pointer types.
template <class T>
struct primitive<T*> : public stack_element {
  T* value;
  primitive(T* aValue) : value(aValue) { };
  ~primitive() { if(value) delete value; };
};

//now, you can reuse your Stack class with stack_element pointer type:
Stack<stack_element*> myStack;
myStack.push(new primitive<int>(4));
myStack.push(new primitive<string>("hello world"));
myStack.push(new primitive<int*>(new int(4)));
//now, retrieving the elements is a bit ugly:
stack_element* elem = myStack.pop();
if(dynamic_cast<primitive<int>*>(elem))
  cout << dynamic_cast<primitive<int>*>(elem)->value << endl;
//..etc.

Of course, you see that this is far from ideal and basically there is no way to get around this. You can, of course, drop the "templatization" of class Stack and just implement it for "stack_element*" (which can be a nested class of Stack). You can also avoid the dynamic_cast if you can restrict the amount of different types needed and provide some sort of type identification virtual method for stack_element (such as "getTypeID" that could output a unique integer for each different type). If you only store types of similar sizes, you can also use a "union" (yes.. in good old C-style) that would replace dynamic polymorphism, if you don't …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The first thing you need to observe is "complexity". Intuitively, finding a random number between [0,n] shouldn't be much more complex whether n is smaller or greater than RAND_MAX. So, just a first look at your implementation reveals that something is wrong if the code is so much larger than the previous version and uses a bunch of temporary vectors too. Pay a little bit of attention to the "expected" complexity and you can know right away if your implementation is effective.

Now, let me give a few inline comments:

int nrand(int n)
{
  if(n <= 0)
    throw domain_error("Argument to nrand is out of range");

  int r;

  if(n > RAND_MAX){
    typedef vector<int> veci;
    typedef vector<veci> vecv;

    int x = 0;

    do { //put the curly braces here, don't make it too easy to get an infinite loop.
     ++x; 
    } while(n % x != 0 && n/x > RAND_MAX);
    //I think the above condition is too easy to meet! this will stop at first iteration because n % x == 0 for x==1, always.

    int y = 0, z = n/x; //please use more intuitive names then "x", "y", "n" and "z"
    vecv rec(x);
    for(int i = 0; i < x; ++i) { //use the usual bounds, the one you had was not correct anyways (it skipped the last element).
      while(y != z) { 
        rec[i].push_back(y); //do you really want to create a vector of size n, which could be 2147483647 (i.e. 8.5 GB on a 32bit computer!)
        ++y;
      } …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I found this quote to be quite nice about your topic: "An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality." -BFree, StackOverflow

@csurfer>>You cannot include a prototype of a function in a class and leave it undefined. Its a compiler error.
That's wrong. Of course you can give a prototype of a function in a class and not provide an implementation for it. The linker will only look for the implementation of the function when it is called, and it will throw an "undefined reference" if you didn't provide it. Also, sometimes the function is not reachable because it is private so its implementation is not needed at all, people use this concept all the time, with the so-called "non-copyable" idiom:

class non_copyable {
  private:
    non_copyable(const non_copyable&);
    non_copyable& operator=(const non_copyable&); 
};

In the above, both the copy-constructor and assignment operator are not reachable because they are private, but the fact that they are there tells the compiler not to generate default versions of those functions. The consequence is that the class and any of its derived classes create objects that cannot …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Basically, if the compiler wanted to inline a recursive function, it would be the equivalent to unrolling a loop. The first rule is that the number of recursions (or loops) has to be determined at compile time. So if your recursive function cannot be turned into a for-loop with a fixed number of iterations, then sometimes the compiler has a setting in its optimization options that determines a small fixed amount of unrolling that it will do before calling the normal function. So it is possible that the compiler chooses to put a few inline copies of the function before it calls it normally (essentially, this will be faster if "usually" only a few recursions are needed, otherwise it makes no difference). Generally speaking, the compiler cannot fully inline a recursive function because it would lead to infinite amount of compiled code. And the special cases are when the recursion dept can easily be determined at compile-time and is very shallow (only a few recursive calls), or when optimization settings prescribe that a few recursions are unrolled (i.e. inlined) before the non-inline function call is performed.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Do you contribute in the boost library?
wow, that's flattering, I wish I did. I think the kind of stuff I program is a bit too specialized (multi-body dynamics, control software and artificial intelligence) for boost which tends to have general use libraries... but who knows, maybe I will someday.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The things between the colon and the curly brace is called the "initialization list". Read this faq on constructors for a good explanation on why this is preferable to assignments inside the body of the constructor.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Why is the implementation of a deleter policy not totally fine for this situation? Check out how boost smart pointers are implemented for example.

Simply put, I would implement it like this (simplified version of the boost smart pointer implementation):

template <class T>
struct default_deleter {
  void operator()(T* ptr) { delete ptr; };
};

struct null_deleter {
  void operator()(void*) { };
};

template <class T>
struct conditional_deleter {
  typedef bool (T::*condition_function_ptr)();
  condition_function_ptr condition;
  conditional_deleter(condition_function_ptr aFuncPtr) : condition(aFuncPtr) { };
  void operator()(T* ptr) {
    if(!(ptr->*condition)())
      //handle the problem by any other way besides throwing an exception!
    else
      delete ptr;
  };
};
//add a function template for ease:
template <class T>
conditional_deleter<T> make_check(conditional_deleter<T>::condition_function_ptr aFuncPtr) {
  return conditional_deleter<T>(aFuncPtr);
};

template <class T, class DeletePolicy = default_deleter<T> >
class smart_ptr {
  T* ptr; //the stored pointer.
  DeletePolicy deleter; //the deleter object (usually takes 0 memory)
  //..implementation..
  smart_ptr(T* aPtr, DeletePolicy aDeleter) : ptr(aPtr), deleter(aDeleter) { };
  ~smart_ptr() {
    deleter(ptr);
  };
};

class socket {
  //...
  public:
    bool isSocketClosed() {
      //...
    };
};

template <class T>
struct checked_ptr {
  typedef smart_ptr<T, conditional_deleter<T> > type;
};

// instantiate with:
checked_ptr<socket>::type my_ptr(new socket, make_check(&socket::isSocketClosed));

With further manipulations, a reference counting or other schemes can easily be put into this deleter policy. If you want to separate the two policies (checking and deleting) just fuse this solution with the previous one I posted.

On a side note, my opinion is that you don't want to design your classes such that an object is in a state …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have no variable called "x" in the function main(), so the statement "cout << secret (x) << endl;" is meaningless. You need to either make a variable "x" and give it the proper type and assign a value to it. Or, just pass a literal constant, like 5, to the function call, i.e. "cout << secret (5) << endl;".

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@firstPerson: read the question: "let's talk about template" and "How do you make this generic?", this is not a OOP or dynamic polymorphism question, but a question on generic programming and template meta-programming.

Now to answer the (simple) question: this question is essentially generic programming 101. You can make a policy class that implements the checking or the no-checking

struct NoChecking {
  static bool checkCondition(/*..some params..*/) { return true; };
};

template <class T, class CheckingPolicy = NoChecking> 
class JustForFun{

    myExecFun(){
         if( CheckingPolicy::checkCondition(/*..*/) ){
               sampleExecute();
         } 
         else{
                cout << "condition doesnt match" << endl;
        }
    }

    sampleExecute(){
          //some operation
    }
}

Normally, the above should be quite alright. The user can provide its own checking policy class with a static bool method for checking the condition, and/or you can also add a bunch of alternate commonly-used policies of your own. If you are worried about the fact that a conditional evaluated which is always true (when the NoChecking policy is used), don't worry.. the compiler will optimize that away for sure (simple branch reduction).

There are also plenty of alternate solutions in the wonderful world of template meta-programming that would be just as good or better. You can also deal with variable parameters, or what give you.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You can also use template specialization with a template... you can avoid the ordering problem of the default template argument. What I mean is this:

//create a placeholder struct for key types
template <class T>
struct key { };

//create a placeholder struct for data types
template <class T>
struct data { };

template <class T>
class list;
  //intentionally left with no generic implementation, to catch illegal uses of list.

//now specialize for key types:
template <class T>
class list< key<T> > {
  //put the implementation for the key-version of list
};

//now specialize for data types:
template <class T>
class list< data<T> > {
  //put the implementation for the data-version of list
};

//instantiate as follows:
list< data<int> > l;
list< key<short> > m;

You can also have a general implementation for key and data with a default for each, without the ordering issue:

template <class Key, class Data>
class list_details {
  //generic key and data implementation.
};

//now specialize for key types:
template <class T>
class list< key<T> > {
  template <class Data = unsigned int> //some default type like "unsigned int"
  typedef list_details< T, Data> type;
};

//now specialize for data types:
template <class T>
class list< data<T> > {
  template <class Key = short>
  typedef list_details<Key, T> type;
};

//instantiate as follows:
list< key<int> >::type a;      //list with "int" keys and default data-type "unsigned int"
list< key<int> >::type<int> b; //list with "int" keys and "int" data.
list< data<int> >::type c;     //list with "int" data …
Intrade commented: Purely awesome. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To turn this into a compilable and runnable program, use this:

#include <iostream> //this will include the "std::cout" stream for output to console.
using namespace std; //this will allow you to avoid writing "std::" all the time.

int mystery (int x, double y, char ch)
{
  int u;
  if ('A' <= ch && ch <= 'R')
    return (2 * x + static_cast<int> (y));
  else
    return (static_cast<int> (2 * y) - x);
}

int main() {
  //what is the output of the following C++ statement?
  cout << mystery (5, 4.3, 'B') << endl;

  return 0; //this is necessary to return a "all went well" result of the program.
};

That's all. Please use code-tags in the future to better format the code in your post.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

#include <cmath>
for that mathematical functions in C++. However, for any of the three methods, there is no need for any mathematical function, just basic arithmetic operators will do.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>do you guys think that using Berkely DB will help towards the saving of the matrix in chunks.
No. This is a database library, it is completely besides the point. It could be used, but it is not any better or simpler than just using iostream, or the boost serialization library.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Oh, yeah, I understand. The problem is that once you reach end-of-file (eof) then you cannot read with the file again because it goes in this error state that prohibits any further file operations. To reset the state, call "file.clear();" at the start of the readLines() function. That should fix it, and don't forget the "endl" on the output.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

About the rendering of the lines at the end, I believe the newline character is not part of the characters that are written to "input" by the function getline(). So the output buffer, which flushes on newlines, never flushes before the application reaches the end. Just add " << endl;" in that printing line of the last for-loop.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are two functions that are _crucial_ for doing random access into a file stream, that is: tellg and seekg. The first will tell you at what position the reading pointer (g) is at the moment and the second will take that pointer to a previously recorded place (obtained from tellg). This allows you to parse the file and "remember" important places, like the start of the tenth last line.

You managed to get a pretty good solution. The only problem is that if you have thousands of lines before the last ten lines, you have to read through the entire file instead of just skipping straight to the end. Here is a somewhat better solution:

#include <cstdlib>
#include <iostream>
#include <fstream>


using namespace std;

bool openFile(fstream &);
int getLines(fstream &);
int readLines(fstream &);

char fileName[20];
char * fileNameptr = fileName;
int totalLines = 0; // I am pretty sure this should start at 0.

streampos tenthLastLine; //use a stream position variable for the tenth last line.

int main(int argc, char *argv[])
{
    fstream dataFile;
    
    if(!openFile(dataFile))
    {
        cout << "Error opening file...closing" << endl;
        return 0;                   
    }
    
    getLines(dataFile);
    
    cout << "Total Lines: " << totalLines << endl;
    
    readLines(dataFile);
    
    system("PAUSE");
    
    return EXIT_SUCCESS;
}

bool openFile(fstream &file)
{    
     cout << "Please enter the file name" << endl;
     cin >> fileName;
     
     file.open(fileNameptr, ios::in);
     if(!file)
     {
         return false;           
     }    
     else
     {
         file.close();
         return true;
     }
}

int getLines(fstream &file)
{
     const int SIZE = 81;
     char input[SIZE];
     string line [SIZE];   
    
     file.open(fileNameptr, ios::in); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I agree with gerard, the std:: is missing for all uses of string and istream or ostream in the header file. Also, the #include <string.h> should be #include <string> because the former is a C library without std::string.

**try to _only_ post the _relevant_ code**

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It's a good start, let me give some comments:

#include <iostream.h>
#include <stdlib.h>

//if you want to use cout and endl later, you should add this line:
using namespace std;

class fraction
{
private:

      int den, num;
      bool checkdata();


public:

      fraction(); //a default constructor is not very useful in this case.
      fraction(int aNum,int aDen); //this can be used to initialize den and num.
      void print();
      //the operators need to operate on objects of class "fraction", as follows:
      fraction operator+(fraction); //actual should be "const fraction&", but for now, this is OK
      fraction operator-(fraction);
      fraction operator/(fraction);
      fraction operator*(fraction);
      
};

/*void fraction:: checkdata()
{
if (den=0 && den<0) //here (den=0) will assign the value 0 to den, it should be den==0 to test if den is equal to 0.

}*/ //this function has no effect that way
//this is more useful:
bool fraction::checkdata() //you can return a bool that signifies whether the test passed or not.
{
  return den != 0; //test that denominator is not zero.
}

fraction fraction::operator+(fraction a)
{
  //fill this yourself
  return fraction; //just return 0 for now.
}

fraction fraction::operator-(fraction a)
{
  //fill this yourself
  return fraction; //just return 0 for now.
}

fraction fraction::operator/(fraction a)
{
  //fill this yourself
  return fraction; //just return 0 for now.
}

fraction fraction::operator*(fraction a)
{
  //this is the simpler one, so I will show how to implement it:
  int newDen = den * a.den;
  int newNum = num * a.num; //just "num" takes the value of num stored in this …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Just read this wiki. There are three easy methods: sum all the number's proper divisors (those with modulus equal to zero) and check if it matches the number; generate one perfect number after another with the given formula until you go beyond the number; check if the bit pattern corresponds to that of a perfect number (the pattern is given in the wiki too).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The one problem that I can see is the if you enter a number that is smaller than the first winning number, the search will drive the middle index to 0. And if the 0th value is still bigger than the number entered, "last" will be set to middle-1 which becomes -1. So, a simple fix is to make the winning condition that you have as "last = -1;" to "last = -2" instead and check at the end "if(last < -1)". That should solve it I think.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should check that ApiHook returns true. Beyond that, I can't help you to find the source of the error. sorry.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You got the curly brackets a bit wrong:

#include <iostream> //omit the .h for the standard C++ libraries.
//#include <stdlib.h> //stdlib.h is a C library that is not really used in C++.

class fraction 
{ //start the { just after the class name
private:

      int den, num;  //these are called "data members"
      void checkdata(); //this is called a "member function" or "method"

public:

      fraction (); //this is the "constructor"
}; //end it after all the members have been declared.

Keep going, and you can post your progress for further comments and guidance. Just posting the code that solves the problem you posted wouldn't be very helpful to you, believe me, it will be better for you if you do most of the work.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, this Delphi code:

var
  MessageBox_Next : function(handle:HWND;tipe:Integer): Cardinal; stdcall;
       
function MessageBox_CallBack(handle:HWND;tipe:Integer): Cardinal; stdcall;
begin
  Result:=MessageBox_Next(handle,3);
end;

ApiHook('user32.dll','ShowWindowA',nil,@MessageBox_CallBack,@MessageBox_Next);

Would be literally translated to:

unsigned int __stdcall (*MessageBox_Next)(HWND handle, int tipe);

unsigned int __stdcall MessageBox_CallBack(HWND handle, int tipe) {
  if(MessageBox_Next)
    return MessageBox_Next(handle,3);
  else
    return 0;
};

int main() {
  //..
  ApiHook("user32.dll","ShowWindowA",NULL,MessageBox_CallBack,&MessageBox_Next,0);
  //..
};

I would suggest you get some more skills in C++, because the above is very simple C++ code that you should easily be able to write yourself if you doing something as advanced as DLL hooks.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

**please use code tags in the future**

The line "set_terminate(MyQuit);" should have been put inside the main() function. Just move it into main() and it will work.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, the calling convention of the DLL functions need to be declared as "stdcall;" to be easily imported to C++.

Second, in both functions ApiHook and ApiUnHook, the parameter MainApi is declared as "var Pointer" which I'm not sure how it translates to C++ (probably to void**). It appears that the assumption that "var Pointer" is equivalent to "void**" is pretty safe, so you might just leave it and try as is. If it doesn't work, you can modify both functions such that the MainApi parameter is a "^Pointer". Check carefully that you change it everywhere that MainApi is used in those functions.

Once that is done, you have two options: run-time or load-time linking.
load-time:
I'm pretty sure that Delphi can output a .lib for the DLL you compile (which is necessary for load-time linking). If you can find that option and generate the .lib file, then all you need in C++ is a simple header file with this content:

extern "C" bool __stdcall ApiHook(char* ModName, char* ApiName, void* FuncAddr, void* HookedApi, void** MainApi, int codigo);
extern "C" bool __stdcall ApiUnHook(char* ModName, char* ApiName, void* FuncAddr, void* HookedApi, void** MainApi, int codigo);

Include that header and add the .lib file to the compilation process for your C++ code. And that should be it. You will use the functions in C++ essentially the same as the code you posted in Delphi, with some "reinterpret_cast<>()" for getting around the hard-typing of C++ vs soft-typing of …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

From a little web searching, graphics.h is part of BGI graphics tools for C that date back to DOS applications when the graphics card was accessed directly via binary registers. Nowadays, that still exists (this is how the starting graphics are rendered by the BIOS and boot-loader before your OS starts up). But this is fundamental incompatible with the windows environment and was essentially abandoned since win32. Your version of turbo C++ dates to 1997 (13 years ago). Although graphics.h was still supported in win9x series via its MS-DOS back-bone (by starting up a MS-DOS session and running the program in there), now, since winNT and later, there is no more MS-DOS, just a "command prompt" which is not the same. Although it looks the same, the graphics are not rendered with BGI because that is dangerous and incompatible with windows.

So, think about it, you are trying to use a C library designed for a 16bit, command-line based OS with no graphics card or mouse support. Your hopes of running this on a 64bit windows 7 environment via a completely outdated C++ compiler and IDE is just ludacris. You will have a very hard time circumventing the "bgi graphics is not supported under windows" error message that you will most certainly get even if you succeed in compiling a graphics.h based program.

Switch your IDE to Code Blocks and use the "with MinGW" download link to have the GNU compiler suite. If it has a …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I didn't know about MagicApiHook, but a quick google search for it revealed this thread which posts the source code for it. Just translate it to C++. I have done quite a bit of Delphi programming too and it is very easy to translate. The other alternative is to compile it to a DLL and use it in a C++ project, I guess that should be easy enough for you to do.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I have never heard of graphics.h, I guess I am too young for that (I only started programming around the time win95 came out, so graphics.h was already outdated!). Here is another thread with some useful info and links. I can't help any further, it appears you should try something else besides graphics.h.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I agree with Ketsuekiame, I don't see any reason why you would "automate" an install of a bunch of software on another computer. Remote desktop to it, or open a secure shell (ssh) to go in and transfer your installation executables (or packages) and run them. It is just as easy as installing them on a local machine. But, of course, they both require that you have access rights to the computer. If you don't have access rights and want to do this anyways, then you are a shameless hacker (scum of the Earth if you ask me!).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

thank you for your answer. I was familiar with the compile-time assert from Alexandrescu (I am consulting his "Modern C++" book almost daily). There are of course many more ways to catch errors at compile-time, but neither of them solves my problem.

Basically what I need is to somehow make "iter2" constant as long as "iter3" exists. The problem is that the only way to do something when iter3 is created and destroyed is via the constructor (or function begin()) and its destructor. These happen at run-time and thus cannot trigger a compile-time error. Since the scope of the variable "iter3" is determined at compile-time, I thought there might be a way to catch that kind of illegal uses of "iter2" while "iter3" is in scope or exists. So the problem is not to do a compile-time assert, but to come up with a compile-time conditional that triggers the assert. I have very little hope at this point and I am contemplating to just not have any error-checking at all (to avoid run-time overhead).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It is dirty, but it is possible (everything is possible). I have no specific clue to give you but I can give you the basic strategy. First, this is an interesting article on dynamic linked libraries (mainly written about Linux's "shared objects" which are the same as DLLs in windows), it gives a good overview of the underlying mechanics. Now, I think you can observe that the function LoadLibrary is from the windows API. So, how to tap into it? Well, if you can modify the executable file before running the program, then you should be able to find the dynamic linking entry (called an ELF header in Linux) which corresponds to the LoadLibrary function. Essentially, you can modify that entry in the executable file to point to a custom version of LoadLibrary that you implemented in another DLL and that forwards the call to the real LoadLibrary function while recording or issuing a message box telling the DLL that was loaded. Essentially, you will have to right a little tool program of some sort that rewrites the linking table of the executable, or maybe there are some already available in the world-wide-web.

This is not necessarily very easy, certainly not safe, and very naughty, but that's the only solution I can think of. I hope this is for a virtuous reason and that you are not some shameless hacker!

EDIT: If all you want is the name of the DLLs that an executable will load …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, the use of all-upper-case for class names is horrible. By convention, all-upper-case is reserved for #define (or MACROs). If this example was from a book, consider changing book.

Now, about your question... first, observe the following: "string" is a class, just like "FLATMATE" is a class. So if you don't have a problem understanding what "string name;" is and how it can be part of class "FLATMATE", why do you have a problem with "DUTY" containing a data member of class "FLATMATE". There is absolutely no difference.

>>any idea what is the name for the "FLATMATE resident "in the class Duty?
The name is "data member" of class FLATMATE, more precisely "private data member" because the default access right in a class declaration is "private" (if you haven't learned access rights yet, it won't take long until you reach that concept).

>>is it an object?
Yes. If you are confused about why it is an object and a data member at the same time, take this analogy: A father can say "this is my son", while the son will say "I am a man". Now that becomes: An object of class DUTY can say "resident is my data member", while resident will say "I am an object of class FLATMATE".

>>And what will happen to the resident in class Duty?
When an object of class DUTY is created, an object of class "FLATMATE" will also be created within the DUTY …