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

Well.. I would say C, C++, and Python are the most main-stream languages because they solve their part of general programming problems. But there are many other programming languages that are specialized to certain areas. But when it comes to general programming problems (like 90-95% of software that is written), nothing beats this trio. But you do find people using alternative languages for general programming problems, like Java, C#, C++/CLI, J#, Delphi, Ruby, Perl, Haskell, etc. etc., some may, arguably, be better in certain circumstances and stuff, but overall C++ rules! (both in terms of feature-richness and wide-spread use)

As for domain-specific languages, there are of course languages like Matlab (for numerical analysis in general), Fortran (for hardcore scientific computing, like programming simulation software to run on super-computers), LabVIEW (digital signal processing and data acquisition), etc. These are in a separate category and they are, of course, extremely linked to what they are applied to. They can't really be factored into any comparison with general-purpose programming languages (well, maybe Matlab can be compared to C++ in the context of numerical analysis, but that is a bit of a stretch).

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

>>Among Java, C, C++ and Python which in your opinion is the most valuable to know?

IMO, amongst the serious programming languages, that is: C, C++ and Python. They each address a different realm.

C is mostly found for very low-level codes that either cannot be in C++ because of platform limitations (like micro-controllers for examples) or because it is simply easier to do very low-level stuff in C than in other languages (typically, hardware drivers are programmed in C).

Python is typically used for very high-level programming. Usually, you find it alongside C++ libraries (so-called "Python bindings"). Typical uses of Python are: writing plug-ins for existing applications; or having applications that are highly customisable.

C++ is typically for everything in between (I would say around 95% or more). C++ can do everything from extremely low-level to extremely high-level, but it sort of gets a little bit inappropriate at the fringes and that's where C and Python come in play. C++ is extremely powerful and is by far the best tool for any typical "number-crunching" programming (like game engines, simulators, complex software (with GUI), networking, artificial intelligence, image processing, etc.). However, at the very low-level (e.g. hardware drivers), some rules of C++ become a bit annoying and C is usually favoured. And at the very high-level, it is hard to completely wash away the underlying mechanisms from the C++ code, and thus, the high-level programming is not as easy as it should be by definition. Often, …

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

I can't give you much book suggestions or basic online tutorial (because my years of learning basic C++ are far behind me), but there is one site (in addition to www.cplusplus.com) that is key resource for understanding and knowing how to program well, that is: http://www.parashift.com/c++-faq-lite/

As for learning C before getting into C++: C is more low-level and require you to deal with memory allocation, arrays, pointers, null-terminated strings, etc., and these low-level processes occur "under-the-hood" of C++ standard library functions and classes. I would say that it is important to understand C code and how it is done such that you have a good idea of what is happening under-the-hood of C++ code. But, don't "learn C" in the sense of becoming proficient at it. Because if you are too accustomed to C programming you run into the danger of moving into C++ programming and wanting to resort to those C functions and constructs that you are familiar with and these are almost always a worse and less-effective choice than their C++ equivalents.

One caveat on that, if you are already familiar with another programming language similar to C (like Fortran, Matlab, Pascal, etc.) and you are comfortable with how procedural programming works (you know concepts like variables, types, identifiers, pointers, parameters, functions, dynamic arrays, stack vs. heap, compile-time vs. run-time, etc.) then you can go straight to C++. So, basically, understanding C before learning C++, is another way of saying, understand …

kvprajapati commented: Well said! +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your .c file is totally fine. The problem is your header file. You shouldn't include the .c file from the header. This causes a circular pattern that will recurse infinitely (.c includes .h includes .c includes .h includes .c ... ad infinitum). Your compiler simply stops this at some limit (1024) such that it doesn't crash your computer (basically it would cause the compiler to run an infinite loop). The proper way to write your header is as follows:

// Change.h

//below is a "header guard" (prevents a header from being included more than once)
#ifndef CHANGE_H
#define CHANGE_H

//include statements would come here. (but not change.c)

class Change
{ private:
    int numTwenties;
    int numTens;
    int numFives;
    int numOnes;
    int numQuarters;
    int numDimes;
    int numNickels;
    int numPennies; 
    
  public:
    Change();
    Change( double dollars );
    Change( int twenties, int tens, int fives, int ones, int quarters, int dimes, int nickels, int pennies );
    
    double AmountInDollars();
    void SetAmount( double dollars );

   // I would probably add a method for setting/getting each of the twenties/tens/etc.
    void SetTwenties( int twenties );
    int GetTwenties();
};

#endif //closes the header guard.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

What you find below seems to do what you want.

for (int q = 0; q < tableCount; ++q)
{
  for (int j = 0; j < outTables[q].Items.size(); ++j)
  {
    outFileDrs.write(&(outTables[q].Items[j].Data[0]), outTables[q].Items[j].Data.size());
  }
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I have to say. The more I read your posts, the more I get the idea that you may not even have written a single line of code in C++ before starting this project of translating a C# library into C++. One thing that is true in natural languages (English, French, etc.) is that no-one is qualified, regardless of how much schooling they have, to translate into a language that is not their native language (this is by law in Canada: you cannot be officially accredited to translate from language A to language B, if language B is not your native language). From what I have seen, in programming, pretty much the same logic applies (except that "native" languages are the few languages in which one is entirely proficient). A programmer mainly proficient in C++ can translate almost any code into C++ code, but never the other way around, because the quality will be horrible if you try to translate into a language you are not totally proficient in. You should maybe consider that you may not be qualified to translate code into C++, because from what I have seen, you seem to go about it quite blindly. If you are doing this for someone, maybe that someone would be better served by an experienced C++ programmer. If you really need to do this yourself, man.. this will be a brutal crash course in C++. Get a good book on C++, it might help.

BTW:
>>It said the …

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

I don't know about that problem about the size of the file. I would suggest you step through the code and/or print out the sizes of all there arrays (size of outTables, outTable.Items, and outItem.Data) to see if the problem is with the file stream or with the construction of those arrays.

Line 10 seems very very wrong to me. From looking at this code, it is clear that whatever is saved in outFileDrs, it is complete garbage (completely arbitrary data). I don't know what you think line 10 is supposed to do, but I can tell you it is not what you think it does. What it does is add up all the values in outItem.Data and store them in the first element of tempData, starting from a garbage value. And all the other elements (from the 2nd to the last) in tempData remain set at garbage values. There is no way that this is what you want. You should clarify what that loop is supposed to do.

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

Welcome to Daniweb!
Please use code-tags around the code that you post.

I don't know where you saw that problems can occur when you have too many semi-colons. Usually, it is the other way around. Many stupid little compile errors can be solved with adding semi-colons. Usually, it is safer to add a semi-colon after each closing }. Also, you have to leave some empty lines at the end of any header or cpp files. Finally, you should always put the statement "using namespace std;" and any other "using namespace XXX;" statements after you have included all headers (not in the middle of the includes as you did). And also, you should never have "using namespace XXX;" statements inside a header file. So, a revision of your code, with these changes, gives this (assuming this is a cpp file):

#include <iostream>
#include <string>
#include <fstream>
#include <comdef.h> // for _bstr_t
#include <string>
#include "stdAfx.h" // note: using old C libraries will sometimes cause these kind of errors you are experiencing.

using namespace std; //put using namespace statements after the #includes above.

int gethandle(string hdlText)
{ // <<<<-------------------------- This is where the problem is... NOT REALLY!
  static string tkr[1000];
  static int lastCache;
  if (hdlText == tkr[lastCache])
  {
    return lastCache;
  };

  int count;
  for (count =1 ; count < 1000; count++)
  {
    if (tkr[count] == hdlText)
    {
      lastCache = count;
      return count;
    };

  };
  for (count =1; count<1000; count++)
  {
    if (tkr[count] == "")
    {
      tkr[count] = hdlText;
      lastCache …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In C++ strings, they are always valid strings (but they can be empty, of course). So, in your case, you should do exactly this:

char testTemp[10];
for (int i = 0; i < 10; i++)
  testTemp[i] = data.at(i);
std::string test(testTemp, 10);
if (test != "Item Name\t")
  return data;

The reason why you see expressions to test if a string is NULL with C-style strings is that they are implemented as pointers to chars, and pointers (of any kind) should always be checked for being NULL before they are used (i.e. dereferenced). I don't know why the C# code had that as well, I guess C# is worse than I thought. In C++, you hardly ever have to use pointer types (if it is good quality code), and the standard string type in C++ reflects that fact.

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

Well, as a basic-level solution, yours is totally fine. It is _correct_ in the sense that it will do what you expect and without error. It is _ok_ in the sense that since you are stuck with code that you cannot or don't want to change that needs regular arrays, it is fine to make this accommodation. Of course, I can suggest a few improvements:

I'm not sure this was one of your operator overloads, but I can point out that you can also overload the [] operator (for indexing) such that you can use your vector class exactly as if it was an array:

class mVec
{
  private:
    float vec[3];

  public:
    mVec();
    mVec(const float * const parray);
    mVec(const float a, const float b, const float c);
    ~mVec();

    mVec operator+(const mVec& param);
    mVec operator-(const mVec& param);

    //define a read-write access to element i, to allow: "mVec v; v[i] = 0.0;"
    float& operator[](int i) { return vec[i]; };
    //define a read-only access to element i, to allow indexing into a "const mVec".
    const float& operator[](int i) const { return vec[i]; };

    //other operators...

    float* useAsArray()	{ return vec; }
};

I don't know if you are familiar with the basic use of templates. If you are, you can simply define your functions (without reimplementing them) such that they except any array-like type (whether it is mVec, or float*, or vector<float>, or float[3], or whatever), as such:

template <class FloatArrayType>
void normalizeVector(FloatArrayType vec) {
  float norm = sqrt(vec[0]*vec[0] + …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If test is a std::string, then you don't need the first comparison with NULL. This comparison is only needed if test is a "char*" (i.e. a null-terminated C-string), and in that case, it wouldn't be done that way. So, the two options are:
C++ style string:

std::string test = "Hello World";
if ( test == "Hello World" )
  std::cout << "test is indeed Hello World" << std::endl;
if ( test != "Hello World" )
  std::cout << "test is not Hello World" << std::endl;

C-style string:

char test[] = "Hello World";
if ((test) && (strcmp(test,"Hello World") == 0))
  std::cout << "test is indeed Hello World" << std::endl;
if ((test)  && (strcmp(test,"Hello World") != 0))
  std::cout << "test is not Hello World" << std::endl;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are a few inefficiencies about your implementation (the push_back() is only one of them). Basically, you should avoid allocating memory within a loop. This is why push_back is inefficient because it re-allocates and copies the memory at each iteration (although STL containers like vector are amortized, but still..). Also, the new allocation of this tempItem at every outer iteration is also very inefficient. I propose something like this:

//First, figure out what the maximum size for tempItem should be:
int maxSize = 1;
for(int q = 0; q < tableCount; q++)
  for(int j = 0; j < inTables[q].Items.size(); j++)
    if(maxSize < inTables[q].Items[j].Size)
      maxSize = inTable[q].Items[j].Size; //notice that using [j] is more efficient than .at(j) (skips useless bound-checking)
//Then, allocate enough memory for tempItem, and do it only once.
char *tempItem = new char[maxSize]; 
for (int q = 0; q < tableCount; q++) //using native int type is more efficient than a special type like "unsigned long int".
{
  for (int j = 0; j < inTables[q].Items.size(); j++)
  {
    //Read the data, and tempItem is guaranteed to be big enough to store the data.
    inFileDrs.read(tempItem, inTables[q].Items[j].Size);
    //Allocate enough space for the data in your vector:
    inTables[q].Items[j].Data.resize(inTables[q].Items[j].Size);
    //Then, just copy, using std::copy (from #include <algorithm>) (or you could use a loop too)
    std::copy(tempItem,tempItem + inTables[q].Items[j].Size, inTables[q].Items[j].Data.begin());
  }
}
delete[] tempItem;

However, I'm pretty sure that the following will work just fine (maybe you should verify that it does):

for (int q = 0; q < tableCount; q++) {
  for …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Maybe I am getting confused between read and write...

Read-> take and store into the stream.
Write-> write out from the stream to the vector.

You are confused about the process. The stream does not store memory. Only the vector<char> store the memory. So, what you do is you start with an input vector<char>, link it to a stringstream object, then, using the stream you can access the memory directly to read-off all those values you need to alter. Then you figure out how large the output vector needs to be. Create an output vector<char> that is of the right size (using resize or through the constructor). Then you link this vector to another stringstream object, which you use to write all those values into the output vector. Finally, you return the output vector as a result of the function.

The C# code that you posted does this in a slightly different (and quite stupid) way. But, hey, what do you expect from a C# programmer anyways?

Anyhow, since this is dragging on, I just translated the C# code you posted, except for the parts between /****/ lines and a few things at the end. I hope that you can figure out the rest, because I cannot make it any clearer at this point (I've run out of things to explain).

#include <iostream>
#include <sstream>
#include "stdint.h"

vector<char> Decode(vector<char>& data) {

    stringstream reader;
    reader.rdbuf()->pubsetbuf(&data[0],data.size()); // create variable        

    // testing patch version
    uint32 version; reader.read(reinterpret_cast<char*>(&version),sizeof(version));
    if (version …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

yes, that's right firstPerson. Thx.

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

Sure you can specify the type in advance using the <>. That is called "explicit instantiation" of the template. But, as I said before, you need to use a function pointer type, this means that you must take the address (using &) of the function before you pass it to the function template. For instance, you could do this:

template<typename t>
void trimr(std::basic_string<t>& s){
    if (typeid(basic_string<char>())==typeid(s))
        trimr<char,bool(*)(char)>(s,&iz_space);
    else
        trimr<wchar_t,bool(*)(wchar_t)>(s,&iz_wspace);
}

But I don't think that the explicit specification of the template arguments is what makes the above work. What makes it work is the & before the function, to make them function pointers.

BTW, have you considered using template specialization to improve your implementation. Here is what you could do:

template<typename t>
void trimr(std::basic_string<t>& s); //leave this intentionally not implemented.

//specialize it for char and wchar_t:
template <>
void trimr(std::basic_string<char>& s) {
  trimr(s,&iz_space);
}

template <>
void trimr(std::basic_string<wchar_t>& s) {
  trimr(s,&iz_wspace);
}

This way, if someone tries to call trimr with anything other than "char" or "wchar_t", it will throw a compile-time error like (for float instead of char) "unresolved reference to trimr with [t = float]".

But, to do it even better, I would suggest using type traits, as so:

#include <cstdlib>
#include <iostream>
#include <cctype>
#include <string>
#include <cwctype>
#include <typeinfo>

using namespace std;

template <typename T>
struct my_char_trait { }; //intentionally left blank.

//specialize for both char types:
template <>
struct my_char_trait<char> {
  static bool is_space(char ch) { return isspace(ch); };
}; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

No, the code you have is not legal. If you are stuck having to use a vector of chars, then I can suggest you do the following workaround:

std::vector<char> outputDrsVector;
outputDrsVector.resize(1024); //make sure the vector is not empty!!! Replace the 1024 by a meaningful number (not a magical number).
stringstream inputDrsStream;
inputDrsStream.rdbuf()->pubsetbuf(&outputDrsVector[0], outputDrsVector.size()); // legal.
unsigned int test;
inputDrsStream.write(test, sizeof(unsigned int)); // correct.

Normally, I would not recommend the above because it requires to be very careful:
This assumes that you have already a vector that is big enough to write all the content to. DO NOT GIVE AN EMPTY VECTOR TO PUBSETBUF. You must preallocate (using resize) enough memory in your vector to contain all the data that you will write to it. DO NOT USE THE VECTOR WHILE YOU ARE USING THE STRINGSTREAM ON IT. Using the vector in anyway after you have passed it to pubsetbuf and before you are completely finished with the stringstream will cause a crash. ALWAYS PASS size() TO THE PUBSETBUF FUNCTION. Do not make up some magic number for the "maximum" size, use the size() function of the vector to obtain its size.

For reading and writing integer values (or others), never use magic numbers for size like the "4" that you put in your posted code. Always use the sizeof() operator. DO NOT ASSUME THAT int OR unsigned int ARE 4 BYTES (32bit) LONG. The sizes of these variables varies depending on the operating system and compiler (this …

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

I'm sorry if I was harsh. It's just that it is sometimes frustrating to see people who seem to think that because their code uses templates that it automatically makes their code "better". The thinking should go the other way around. If you want to write really good code (or use a fairly clever design paradigm), you will often end up _needing_ templates to realise it. What you have posted (or at least what your code is doing) is very simple and does not require templates and thus, making use of templates is not a good thing, and it does not add any value or quality to the code (in fact it makes it worse in this case).

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

You forgot to take the address of the functions. Your lines 32 and 34 should be like so:

trimr(s, &isspace); // notice the &
trimr(s, &iswspace); // notice the &
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

different return types be supported by one function so you can use int, float, double, etc vs making several of the same function with different return types.

Your definition of the use of templates is completely wrong (or at least extremely reductionist). First of all, what you are describing is "function overloading" (you can use function templates to have the same effect but it is usually worse than overloading, certainly not in the code you posted). And having different return types for the functions is not possible in neither function overloading nor function templates. The C++ compiler cannot resolve which function to use based only on the return type. This is why you cannot have function overloads or function templates that only differ by the return type. This is exactly the error that your compiler is giving you for the function showWeaponSpecs() because it does not have a parameter whose type depends on the template argument. You can fix it by either not using function templates for the above code and use a void return type (highly recommended!), or by using a dummy parameter, or by instantiating the function call explicitly "M16A4.showWeaponSpecs<int>();".

I suggest to read up seriously on templates because they are so much more powerful than what you are using them for (in fact, what you are using them for is a travesty! IMO). And as firstPerson already pointed out, if you call the function with the wrong type, you will get a compile-time error inside your …

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

Well from a vector<char> is probably not the easiest thing. A vector of chars is not a good way of representing a buffer. You should use either a static or dynamic array or the stringbuf directly. Assuming a static array of chars, this little program shows quite simply how to use stringstream and linking it to a external buffer you have already:

#include <iostream>
#include <sstream> //include the header for the stringstream and stringbuf classes.

using namespace std;

int main() {
  char buf[42]; //say you have a static buffer of chars and you want to read and write to it.

  stringstream my_stream; //create a string stream that will be used as the buffer.

  my_stream.rdbuf()->pubsetbuf(buf, 42); //link the string stream to your static buffer.

  //now you can do any kind of binary or formatted reading and writing operations you like, via my_stream:

  streampos starting_pos = my_stream.tellp(); //recording the start position is always useful. 

  my_stream.write("Start here!", 12); //writes a null-terminated string to the stream.

  unsigned int value = 34;
  my_stream.write(reinterpret_cast<char*>(&value),sizeof(unsigned int)); //writes a 32bit unsigned integer to the stream, in binary format (will span 4 characters).

  my_stream.write("not a null-terminated string", 28); //write a set of characters (no null-termination) 

  
  my_stream.seekg(starting_pos); //go back to the start to see if we can read the content again.

  string test;
  getline(my_stream,test,'\0'); //read a null-terminated string in the variable "test".

  cout << test << endl; //print out the result.
  
  for(int i=0;i<42;++i) { //this loop will print out the content of buf (with # marks for null-characters).
    if(buf[i] …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You forgot to give an initial value to "count" on line 132. Initialise it to zero and it should work. However, there are a few additional changes to make, listed below. But overall, I would say great job! A quality of programming rarely seen at your level!

Small changes:
1) At line 26, you should declare the variable bingo as a "string", it will make it a lot better (right now you actually have a memory corruption problem because bingo is a pointer that points to anywhere and you are overwriting that memory and that's not good). You could also use a fixed array (i.e. "char bingo[6]") but that just useless trouble. So, change the line 26 to "string bingo;".
2) As said before, at line 132, add an initial value to count, i.e. "int count = 0;".
3) You have a small typo at line 140, you used a single equal sign where there should be two.
4) Lines 179 and 208 should be changed to reflect the change of the type of bingo. In other words, it should be "bingo = " ";" (five spaces).
5) The string comparison at line 215 should also be changed to "if(bingo == "BINGO") {".
That's it! I compiled it on my computer and it works like a charm! Pretty fun game too!

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

First, the header for the MessageBox is just the "windows.h" header. That is for most straight Win32 API calls, like MessageBox and many others of the like.

For the second solution you just posted. Normally, when you design a form (i.e. place buttons and menus and stuff on the form), it will generate a class with the name you gave to the form that you created. Say I design a form that I call "MainForm", then the GUI tool (MFC or Qt or whatever) will generate a header and a cpp file that declares and implements this MainForm class. Say I add a button to it and define an event that is triggered from clicking the button. Then, the header might look something like this (the actual class and function names might differ in your GUI tool):

//... some includes and stuff before ...

class MainForm : public TForm {
  // ... some stuff
  public:
    TButton Button1;

    void OnButton1Click();

    //... some more stuff ...
};

Now, what you can do is design another form for your dialog with some message label on it and some caption or whatever else you want. Let's call it MyDialogForm. Again, as before, when you design this form, the GUI tool will generate a header and cpp for this form to work. If you include this header from the MainForm.h and add the cpp to the build of your main application, you should be able to, for example, make a data member of …

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

You need to compile it with this command-line:

g++ main.cpp BINGO.cpp -o BingoGame

Or if you are using Visual C++, you need to make sure that main.cpp and BINGO.cpp are both part of the project "sources" and that the directory in which your BINGO.h file is is part of the "include paths". At first, you should just try to put all the code in one file (content of BINGO.h, then the content of BINGO.cpp and then the content of main.cpp) and make sure that compiles and works without error. After that, you should worry about splitting it up into different files.

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

A few observations:
1) You shouldn't use headers like <string.h> or <time.h>. These are deprecated. You should use <cstring> and <ctime> instead (notice "c" in front, and no ".h"), these are versions of the same old libraries but that will compile more easily with C++ code and compiler.
2) In your class "game" declaration, line 21, 27 and 28 are illegal. If you want to give a value to a data member of a class, they need to be both static and constant. As so:

class game {
  //...
  private:
    static const int size = 25;
   //...
};

3) When you are calling the functions in the main function, you need to give parameters to the function that you call. All line 11 to 15 (in the last segment) are illegal. These are not function calls but they are function prototypes (or declarations) (which are not allowed inside a function, for your practical purposes). I cannot change all those function calls for you because I don't know exactly what parameters they should be given, but here is a simple example:

#include <iostream>

void myFunction(int aParameter); //this is called a function declaration.

void myFunction(int aParameter) { //this is the function's implementation.
  std::cout << "The parameter is " << aParameter << std::endl;
};

int main() {
  myFunction(42); //this is a function call (with a literal parameter);
  int a = 24;
  myFunction(a); //this is a function call (with a variable passed as the parameter).
  return 0;
};

4) Your …

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

It would be: (don't use firstPerson's code, its faulty.. sorry fP..)

int main(){
  unsigned char c1 = 0x56;
  unsigned char c2 = 0x78;
  unsigned char c3 = 0x92;
  unsigned char c4 = 0xF0;
  int combined = ((c1 << 24)| (c2 << 16) | (c3 << 8) | (c4 << 0)); //construct 32bit unsigned integer from 4 unsigned chars (i.e. bytes).
  cout << "Combined = " << showbase << hex << combined << endl;
  
  //now, to reconstruct the four bytes:
  unsigned int byte1 = (combined >> 24) & 0xFF;
  unsigned int byte2 = (combined >> 16) & 0xFF;
  unsigned int byte3 = (combined >> 8) & 0xFF;
  unsigned int byte4 = combined & 0xFF;
  cout << "Byte1 = " << showbase << hex << byte1 
       << "Byte2 = " << showbase << hex << byte2
       << "Byte3 = " << showbase << hex << byte3
       << "Byte4 = " << showbase << hex << byte4 << endl;
}

If you want to store a vector of bytes in a way that is closest to the type byte, you should store them as "unsigned char" not "char", you run in the danger of chars being interpreted as either ASCII characters or as signed integers (either one is not what you want, from looking at the C# code).

However, I must mention. Using a vector of chars (or unsigned chars) is far from being the easiest thing to do in this case. I would suggest that you look at

MasterGberry commented: Very thorough explanation :) +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Check the compatibility. fwrite is "deprecated" on newer versions of windows. That might be the problem that causes the crash. Maybe running in compatibility mode or changing to code to use ofstream instead of fopen/fwrite.

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

If you are using Windows, i.e. Win32 API, then you can use the following function (as suggested before):

MessageBox(NULL,"An error has occurred because you didn't use this program correctly!", "Error!", MB_OK);

If you need something more fancy (like different buttons or display), then you can make your own form with whatever GUI tool you are using. Any GUI tool, like MFC, Qt or wxWidgets, has a way to create the form and usually, you have a function like "show" or "execute" that will show the window, and usually, that function has a parameter which is the handle of the form from which you are creating this sub-form (usually called the "Parent"). This will generate a new form on top of the current form, you can also disable the current form until the sub-form (error message) has been clicked away or dealt with. You should be able to find this in your particular GUI tool (in the help files).

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

This scenario you are describing is classic in concurrent programming. Most of the time it is referred to as the consumer-producer scheme or just called a buffer between two processes. For multi-threading, I highly recommend using the Boost.Thread library. It is very nice and easy and it will form the basis of the C++ standard threading library (coming up in a few months with the new standard C++0x).

Below is a simple example of a consumer-producer scheme implemented with Boost.Thread. The producer thread fills the buffer with integer values and the consumer grabs those values and outputs the square. This is a classic implementation: it uses a simple queue (FIFO) for the buffer and uses a mutex to prevent the two threads from accessing the queue at the same time. This is not by any means the best implementation (or even a good one), it is just a simple example to show the mechanics of it.

#include <boost/thread/thread.hpp> //this will require linking with "-lboost_thread"

#include <iostream>

#include <queue>

struct int_buffer {
  std::queue<int> data; //holds a simple queue of integer values.
  boost::mutex data_mutex; //holds a mutex that can be used to gain exclusive rights to the buffer.
};

//class for the producer.
class producer {
  private:
    int_buffer& buf; //internal reference to the buffer.
  public:
    producer(int_buffer& aBuf) : buf(aBuf) { };

    //this function is the one that boost::thread object will call to execute the thread.
    void operator()() {
      for(int i=1;i<=1000;++i) {
        boost::unique_lock<boost::mutex> lock_here(buf.data_mutex); //obtain exclusive lock.
        buf.data.push(i); //add …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You made a typical logic error. Your algorithms for min is inverted. That is, your min function will actually return the maximum value. Just change the name and you have the max function done. The little bit of logic confusion is that when you are looking for the minimum, you should first set your variable to the maximum possible number (MAX_NUM or some other large number) and then replace it with every number in the array that is smaller than the one you have stored currently. You have done the opposite in your min function, you first set to MIN_NUM and then replace its value by every element that is bigger than the current one... at the end, that will get you the maximum value in the array.

BTW, don't let your ego take a hit because of this silly mistake, this is actually a surprisingly easy-to-make error (I find myself doing it too, once in a while).

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

If you see a class template declared as so:

template <class SomeType>
class Foo {
  //...
};

It means that to use this class, you need to provide another class (or type in general) as argument to the template. The STL queue type is similar (except that it has a few more template arguments that have default values). This means you need to put some sort of type name as template argument, as in the following, for a queue of integers:

std::queue<int> myQueue;

From the looks of your code, it seems that really what you want to have is just like in the above, that is, a queue of integers. So, your class should be declared as:

//#include <iostream>
//#include <fstream> //don't include unnecessary headers (include them in the cpp instead.
#include <queue>
//using namespace std; //don't import namespaces in a header file.

//template <int T> //T seems to be useless and BruteForce does not need to be a class template.
class BruteForce {
  private:
    int currentItem, nextItem;
    std::queue<int> q;
  public:
    void MakeQueue();
    void GetPercepts();
    int reflexAgent (int,int);
    void DisplayInfo();	
};

The reason you had the error that you had is because you declared BruteForce as a class template with an integer-valued argument. Because template arguments can be either a type name (or a variation of that) or a constant value (known at compile-time) of some primitive type (int, float, double, char, etc... but not pointers or string types). This is actually an extremely powerful feature, but …

rcmango commented: Thankyou! Your feedback helped me a great deal. +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is why I would recommend CodeBlocks as an IDE because it is made for and comes with GCC (from MinGW of course), for free, single installer, no trouble, out-of-the-box kinda thing. And as an IDE, CodeBlocks is "critically acclaimed". You should try it out.

The reason why an up-to-date IDE and compiler is important is mostly because the C++ standard and standard libraries are constantly upgrading (especially now with the new, upcoming standard C++0x). An older version might do fine for some time for some basic programming but it will get very annoying when you start to try more advanced stuff and you will get extremely frustrated and demoralized if you are trying example codes from, say, www.cplusplus.com, and they are not working on your out-dated compiler and don't understand why.

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

Dev-C++ is outdated. The version of GCC that comes with it is 3.4! The current version of gcc is 4.4.5. We have also encountered several people posting threads on this forum about problems related to DevC++, including compatibility issues with the newer versions of Windows (Vista and 7). So I wouldn't recommend it for those reasons, regardless of the nice features it may have.

CodeBlocks or VS (Express) would be the way to go if you want an IDE. Certainly for the compiler alone, GCC is the best (that is free.. if you have an endless money supply, you could get the intel compiler (ICC) which is the only one that is better than GCC).

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

It just hit me. Say you have:

template <LPSTR Type>
class Foo { };

How is the compiler supposed to know that these two types are the same:

typedef Foo<"my type name"> myType1;
typedef Foo<"my type name"> myType2;

It has to compare the template arguments to determine if the types myType1 and myType2 are the same. The problem is that comparing char pointers together will not succeed if the actual literal string is the same, the pointer actually needs to be the same, which will never happen.

So, that confirms a little hunch I had when looking at your code that it was kinda weird to see a pointer type as a template argument. I suggest you use only non-pointer primitive types as template arguments.

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

What should go in the cpp file is the following:

template <DWORD Style,LPSTR Type>
WndObj<Style,Type>::WndObj () {}; //Definition or implementation of constructor.

template class WndObj<>; // Explicit instantiation of the default template.

typedef WndObj<> Button; //whatever this is.. doesn't matter.

The point is that if you want to use class or function templates whose code is in a cpp file that you want to compile as you usually compile cpp files (not including them at the bottom of a header file or something like that), you need to provide an explicit instantiation of the template for each possible instantiations of that template that you might want to use. Of course, in many cases, this is not possible and you have two other options: putting the code all in the header file or including the cpp file for each new template instantiation you might want to use.

That second option can be done as follows:

//in Foo.h:
#ifndef FOO_H
#define FOO_H

template <class T>
class Foo {
  public:
    Foo();
};

#endif

//in Foo.cpp
#include "Foo.h"
#include <iostream>

template <class T>
Foo<T>::Foo() {
  std::cout << "Foo constructor was called!" << std::endl;
};

//in Bar.h
#ifndef BAR_H
#define BAR_H

#include "Foo.h"

class Bar {
  private:
    Foo<Bar> Obj;
  public:
    Bar();
};

#endif

//in Bar.cpp

#include "Bar.h"

#include "Foo.cpp" //include the cpp file such that it gets compiled.

Bar::Bar() { 
  std::cout << "Bar constructor called!" << std::endl;
};

That's it, hope it helps.

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

Did you initialize the list "Seats". If it is empty, then that would explain your error. Make sure it is not empty.

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

It looks like you have a fixed number of elements in the table and they are simple bool type. I would suggest you use either a static array or a class vector instead of list. The error you are reporting is weird... normally, this should execute just fine. The error is either in the definition of Table (and GetSeats()) or that you have some non-standard (and faulty) implementation of the C++ STL. Please provide details on the definition of Table and what platform this is running on. Maybe you could try using "vector" instead of "list", just for a quick-fix of the problem.

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

I'm assuming that you know that when you click on "run" in VS, all it does is compile your project into a .exe, that you can find somewhere in your project folder, and then executes it. Finding that exe and double-clicking on it will run it "outside" VS. But that's not the end of it.
If you want to _distribute_ your application, there are two things (that I can think of) that you need to worry about:
1) Compile your application in RELEASE mode (not in the default DEBUG mode that it usually gets compiled in). This will purge out any debug symbols and other things that generally facilitates debugging but is generally a bit slower to run.
2) Follow these guidelines. This will tell you what you need to distribute or install along-side your application if it is to be run on another computer that doesn't have VS. Usually, you try to limit those external dependencies as much as possible.

Beyond that, I guess you might want to take your program and run it on a few other computers (from friends, colleagues, or school terminals) to see if there are any compatibility issues (try to find computers with minimal other installations and different versions of Windows).

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

Just for fun, I cooked up a little algorithm of my own, without going as far as getting into bit operation-style algorithms. So, in a few minutes or so I got this algorithm which I think is fairly elegant and short:

void genPrimeNumbers(int n) {
  vector< pair<int,int> > accum;
  accum.reserve(n);
  accum.push_back(pair<int,int>(2,4)); 
  cout << endl << setw(20) << 2; cout.flush();
  
  for(int i = 3; accum.size() < n; ++i) {
    bool is_prime = true;
    for(vector< pair<int,int> >::iterator it = accum.begin(); it != accum.end(); ++it) {
      while( it->second < i )
        it->second += it->first;
      if( it->second == i ) {
        is_prime = false;
        break;
      };
    };
    if(is_prime) {
      cout << "\r" << setw(20) << i; cout.flush();
      accum.push_back(pair<int,int>(i,i+i));
    };
  };
};

It just prints out the values and I have checked that it works.
The performance is reasonable given the low level of sophistication of the algorithm:
gets the first 100,000 primes in 5.37 seconds
gets the first 1,000,000 primes in 545 seconds
That is on a 2.8 GHz processor (the program is single-threaded so it uses only one of my 8 processors) with 8M of L3 cache... and the rest of the specs is not so relevant.

EDIT: For the record, the performance is about 20 times worse with the -O0 flag instead of the -O3 flag (-O4 or -O5 made no further improvement).

Clinton Portis commented: fast algorithm. few lines of code. +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your prototype for bf01:

string bf01(int);

Does not match your definition:

string bf01(unsigned int a) {

Matching the two should solve your problem.

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

You have to also add the libb.so to the compilation of atest. Use the following command line to compile atest:
g++ -Wall -L/vol/cuma/sandbox atest.cpp -la -lb -o atest

Notice the addition of -lb

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

Read this.

In the link you will find a good enough explanation why it is not good to throw pointers. My take on it is: What if the dynamic allocation fails and throws an exception of its own? Basically, in that case, you will never reach the actual throw statement, you might not catch the exception and then you will never know where your program actually failed. Throwing by value (temporary) and catching by reference is the way to go.

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

Ok, then consider this addition:

//SOLVER_BASE_H

#ifndef SOLVER_BASE_H
#define SOLVER_BASE_H

// Forward declaration.
class MathematicalMethods;

class SolverBase {
  protected:
    virtual double computeValue( double& value ) = 0; //pure virtual function in the base class.
  public:
    friend class MathematicalMethods;
};

template <class T>
class SolverFunctor : public SolverBase {
  public:
    typedef double (T::*EvaluationFuncPtr)(double&);
  protected:
    T* ObjPtr;
    EvaluationFuncPtr FuncPtr;

    virtual double computeValue(double& value) { 
      if((ObjPtr) && (FuncPtr))
        return (ObjPtr->*FuncPtr)(value);
      else
        return 0.0;
    };
  public
    SolverFunctor(T* aObjPtr, EvaluationFuncPtr aFuncPtr) : ObjPtr(aObjPtr), FuncPtr(aFuncPtr) { };
    virtual ~SolverFuncPtr() { };
};

#endif


//SOLVER_H
#ifndef SOLVER_H
#define SOLVER_H

// Include statements.
#include "MathematicalMethods.h"

class Solver {
  private:
    SolverFunctor<Solver> mFunctor;
  public:
    double execute( double& value ) //notice, any name
    {
        return 2.0 * value;
    }; 

    Solver() : mFunctor(this,&Solver::execute) {}; //create the functor in the constructor.

    ~Solver(){};

    void setMathematicalMethod( MathematicalMethods* mathematicalMethod ) {
      mathematicalMethod_ = mathematicalMethod;
    };

    void solve() {
      mathematicalMethod_->setSolver( mFunctor ); //pass the functor to the mathmethods.
      mathematicalMethod_->execute();
    };

  private:
    MathematicalMethods* mathematicalMethod_;
};
#endif


//MATHEMATICALMETHODS_H

#ifndef MATHEMATICALMETHODS_H
#define MATHEMATICALMETHODS_H

// Include statements.
#include <iostream>
#include "SolverBase.h"

class MathematicalMethods {
  public:
    MathematicalMethods(){};
    ~MathematicalMethods(){};

    void setDoubleTakingFunction( SolverBase* pointerToSolver )
    {
      pointerToSolver_ = pointerToSolver;
    };

    void setValue( const double& value )
    {
        value_ = value;
    };

    void execute()
    {
        std::cout << pointerToSolver_->computeValue( value_ ) << std::endl;
    };

  protected:
    SolverBase* pointerToSolver_;

    double value_;
  private:
};

#endif // MATHEMATICALMETHODS_H

This solution is basically somewhere in-between my first and second original suggestions. The class SolverFunctor is an adaptor, it allows you to adapt a class you have already (Solver) with some …

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

I don't think I can give examples that are any clearer than those I already have posted. I understand your application and I have implemented similar problems many times before (optimization methods and AI methods often involve the same basic setup of a function evaluator and a solver or optimizer). I use either one of the two methods that I previously posted (which one I choose depends on minor details only). Take a second look at them... really all you need to do to adapt it to your problem is to change the names, I'm not gonna do that for you.

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

>>How can I draw the quad to a SDL_Surface or a GLuint(texture), so I can combine them later?
I don't know exactly how to do that, but I know it is not the best/easiest way to do it (in fact, it is probably the worst way). What you want to do is render-to-texture. This can be done in OpenGL. Don't use SDL surfaces to do that, OpenGL is far more powerful, faster and more flexible. I'm not so up-to-date on OpenGL coding so I can't really give you specific functions to use and all, but I would suggest you look up the topic of "Render to Texture in OpenGL". As it says, you can basically render an entire 3D scene onto a texture (internally stored on the graphics card) and then apply it to another object in the scene that actually gets drawn on the screen. They can do some pretty cool effects with this nowadays (especially with shaders). But the last time I implemented this type of effects (almost 10 years ago), the graphics cards didn't have the render-to-texture feature (let alone shaders) and the code I managed to hack-up to achieve this was pretty ugly and slow (almost as bad as your idea of copying the SDL_surface onto a texture, but in those days there wasn't too many possibilities), so I can't recommend anything more contemporary.

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

Look at all the variables that are used by your functions and put them as parameters.

One (retarded) way to do this is to try and compile the code without any parameters to the functions. Then the compiler will throw a bunch of errors like "ErrorZZZZ: in function 'yyyy': identifier xxxx not declared in this scope" which means the function 'yyyy' uses a variable 'xxxx' that used to be global and now needs to be a parameter to the function. Just add all such variables that are reported and repeat until in compiles successfully.

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

>>or is it wiped clean when it is restored back to the O/S for use?
No, it would be wasteful to "clean" the memory. In fact, what does "clean" really mean.. setting all bits to 0? or to 1? or to some other pattern? The next process or chunk of code that is going to use that piece of memory will ignore whatever was there before, so it doesn't matter to what values the bits are set to in the free blocks of memory because nobody cares. It is almost always like that with computer memory. For example, when you delete a file from your harddrive, it doesn't wipe the memory clean, it simply removes the entry for that file in the filesystem (the part of the harddrive that keeps are record of all the files and folders). That way, the file is virtually unaccessible and effectively deleted, but its memory is still there (at least until new files are written and possibly overwrite that memory). Even formatting the harddrive won't wipe out this memory (usually only creates a new empty filesystem).

As Narue said, the heap mechanisms are usually highly dependent on the implementation. However, there is another possibility that is often the case when you delete memory allocated from the heap. That is, the memory is released back to the heap, but not to the OS. The heap usually gets a chunk of memory from the OS and then allocates parts of that chunk to the …

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

The errors you have posted are due to old (very old.. from the days when 16bit computers where common-place) C code that uses these "far" and "huge" keywords for the pointer type "DIBPTR". These keywords are completely obsolete nowadays. I guess they are not supported by C++ compilers (one of the few special features of C that has not been kept backward-compatible in C++). So make sure that all the code that uses this sip.h gets compiled by a C compiler (gcc) and usually all files ending with .c should also be compiled by a C compiler (although the guy who wrote the code may have been sloppy with this as people sometimes write C++ code in .c files because they are stupid). I'm not in any way familiar with CodeBlocks build system so I cannot tell you how to make this work (if you are really hoping to compile this cross-platform, I might suggest you use cmake for the build system).

For a quick-fix of your error above, you could just remove the far and huge keywords and it should work. However, this error might just be the tip of the iceberg. Compiling very old C code in a C++ compiler or interfacing it to C++ code is usually difficult and sometimes it might be easier to just re-implement it in C++ (or at least C-style code that is usable with a C++ project).

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

>>ReadUInt32() is a 4 byte integer, right? So technically I am reading 4 bytes into table.Type? Or does it do something else?
If you need integer types of fixed length, you should use stdint.h or cstdint (depending on what your compiler can support). Check this SO thread on the subject. For the second part, usually if a function is called "ReadUint32" it probably means that it is returning (reading) a value of type uint32 (32bits = 4bytes, unsigned integer).

>>Can (uint) be applied in C++?
Sure. Usually it is written as "unsigned int" (but most compilers will also accept uint as a shorthand).

For the rest I have absolutely no idea. In fact, you didn't mention from which language you are translating this code. In what programming language is the code you posted? I cannot tell and have no idea what the "=>" syntax is supposed to mean (maybe equivalent to "->" in C++, just as a guess).

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

I think your application would be better (or more easily) solved with the use of dynamic polymorphism. Consider something like this:

//SOLVER_BASE_H

#ifndef SOLVER_BASE_H
#define SOLVER_BASE_H

// Forward declaration.
class MathematicalMethods;

class SolverBase {
  protected:
    virtual double computeValue( double& value ) = 0; //pure virtual function in the base class.
  public:
    friend class MathematicalMethods;
};

#endif


//SOLVER_H
#ifndef SOLVER_H
#define SOLVER_H

// Include statements.
#include "MathematicalMethods.h"

class Solver : public SolverBase {
  public:
    Solver(){};

    ~Solver(){};

    void setMathematicalMethod( MathematicalMethods* mathematicalMethod ) {
      mathematicalMethod_ = mathematicalMethod;
    };

    void solve() {
      mathematicalMethod_->setSolver( this );
      mathematicalMethod_->execute();
    };

  protected:
    double computeValue( double& value )
    {
        return 2.0 * value;
    };

  private:
    MathematicalMethods* mathematicalMethod_;
};
#endif


//MATHEMATICALMETHODS_H

#ifndef MATHEMATICALMETHODS_H
#define MATHEMATICALMETHODS_H

// Include statements.
#include <iostream>
#include "SolverBase.h"

class MathematicalMethods {
  public:
    MathematicalMethods(){};
    ~MathematicalMethods(){};

    void setDoubleTakingFunction( SolverBase* pointerToSolver )
    {
      pointerToSolver_ = pointerToSolver;
    };

    void setValue( const double& value )
    {
        value_ = value;
    };

    void execute()
    {
        std::cout << pointerToSolver_->computeValue( value_ ) << std::endl;
    };

  protected:
    SolverBase* pointerToSolver_;

    double value_;
  private:
};

#endif // MATHEMATICALMETHODS_H

If you absolutely want to use functors or other concepts similar to that, I would recommend doing something similar to the following implementation (which is something I have posted a few times already on older threads on this forum... it is quite trivial to adapt this to your application, by just making the function take and return a double):

#include <iostream>

//define a default policy class for all the responder policies 
struct NoRespondPolicy {
  void operator()() {
    std::cout …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

When an object is create, that is, at run-time, all the methods already exist (they are created at compile-time). Those 4 answers make no sense that way. If you create an object, why would it need to create its constructors? It can only be created once. Either the question is wrong (not termed properly) or you are back to square one because none of those answers would be correct.

When an object is created (at run-time) it creates its base class(es), its data member(s), and the new entries of its virtual table if it has/needs one. If you stretch the definition of "create an object" to "object = new Class;", then you might say that an "area in memory is created" for the object and "an entry for that area of memory is created by the heap". That would bring the count to 5, but that is stretching it (and I doubt that your prof meant to involve dynamic allocation and the heap in the answer).

Ask your prof... I suspect the terminology is a bit sloppy because taken to the word I cannot possibly think of 6 things that are created at run-time when the constructor of a class is invoked (and knowing exactly what gets created when a constructor is invoked is pretty elementary and necessary knowledge for an experienced programmer like me, and the others who posted here).