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

What Narue says is entirely correct.


>>WHy does the loop terminate after 13 iterations?

Your stack-frame will look like this: 8 bytes for the char-array (ca) (aligned at 4 bytes, since it needs 5 bytes, it will take up 8 bytes as the smallest multiple of 4 bytes), and 4 bytes for the char-pointer (cp), that makes 12. Your compiler probably fills the stack-frame with some special value (used while debugging), so you hit a 0 only when you reach the end of the stack-frame. But I don't know why the byte after the end of the stack-frame is always zero, that's why they call this undefined behavior. For instance, on my computer, it always stops just after the end of the char-array, as if it was a null-terminated string.

Undefined behavior really just means that there is no way to be sure what will happen, all bets are off. But understanding why it can behave in certain ways is good, because it might help you to recognize the symptoms if you have code with such a problem.

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

If your problem corresponds to iamthwee's interpretation, then his solution is appropriate.

If your problem is that you want to create a vector of arbitrary size where each element is one of the four color-strings, picked at random. Then, a simple solution is to map each color to a number and generate the numbers randomly (e.g. with rand() for a quick and easy solution). As so:

#include <map>
#include <string>
#include <ctime>
#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
  map< int, string> words; 
  words[0] = "red";
  words[1] = "blue";
  words[2] = "green";
  words[3] = "yellow";

  srand((unsigned int)time(NULL));
  vector<string> v(10); // create a vector of 10 elements.
  for(vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
    *it = words[rand() % 4];
    cout << *it << endl;
  };
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Don't bump a three year old thread to ask an unrelated question. If you can't find the answer to your question by looking on Daniweb or on the web at large, then create a new thread for your question.

And to answer, to convert a string to a float, you do:

float toFloat(const std::string& str) {
  float result;
  std::stringstream(str) >> result;
  return result;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>how to print aId varible by using the getid function in vehicle class?

Vehicle v;
  std::cout << v.getId() << std::endl;

>>why we don't put refrence to the parameter capacity

Because it is not necessary.

>>the output for vehcile id is incorect
>>let say i have 5 vehicles, then all the vehicles have the same id which is 5

I'm no psychic, a vague explanation of your code is not going to tell me why it doesn't work.

>>how to use function with vector?

You use the function on the elements of the vector, not on the vector. You access the elements with any of the many function in vector that allows for that. For example, the iterators (with begin() and end()) or the index and operator [] or the function at(). Once you have the element of the vector, you just call the function on it. You do this already in your code, in the loop at the end.

>>i need to create some function then i want to use them in the main function but when i compile, all the varibles in my functions is not declearet
>>how to avoid this problem?

Again, there are no psychics reading your posts.

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

>>Are there are any advantages of using Linux over Windows for programming?

hehe.. Do you really doubt it? Linux is far more comfortable for a programmer. There is only one compiler (or at least, one primarily used), which is GCC, so you don't get any problems with interfacing libraries or anything, all is uniform. All libraries and sources and everything is just one "apt-get install" command away. You never have to worry about linking issues. A host of great tools are available open-source and for free. etc. etc. Windows doesn't even compare. The motivation for using Windows is to distribute your app in the most used OS, but it is a terrible development environment, every other OS that exists is superior, coming from a programmer's perspective. But it's good to develop cross-platform code such that you can be fairly confident that compiling under Windows won't entail too much trouble. But the daily programming / compiling / testing / debugging is far more productive under Linux (even if not an expert with linux commands or anything).

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

Well, while m4ster_r0shi is going at it, I might flex my C++ muscles too...

I just wanted to make the point that doing things at compile-time with meta-programming techniques doesn't have to be really complex and elaborate like m4ster_r0shi's example, especially with C++0x support. For this problem, you could simply do:

#include <iostream>
#include <string>

const char alphabet[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

template <unsigned int Size, unsigned int Index>
struct decoding {
  static constexpr std::string value(const int (&arr)[Size]) {
    return std::string( (arr[Index] - 1) / 52 + 1,
                        alphabet[(arr[Index] - 1) % 52] ) 
           + "\n" 
           + decoding<Size, Index + 1>::value(arr);
  };
};

template <unsigned int Size>
struct decoding<Size, Size> {
  static constexpr std::string value(const int (&)[Size]) {
    return "";
  };
};

template <unsigned int Size>
constexpr std::string decode(const int (&arr)[Size]) { return decoding< Size, 0 >::value(arr); };

int main() {
  constexpr int input[] = {1, 3, 25, 26, 27, 30, 51, 52, 53, 59, 80, 103, 104, 105, 110};

  std::cout << decode(input) << std::endl;

  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As for the libraries, I would recommend to use well-established cross-platform libraries. For your purposes, SDL and/or OpenGL are candidates of choice. Start with SDL and add OpenGL when you want to take your graphics one step further.

Programming a graphics computer game is a lot different from simple console programs. There are several things to handle.

1) Multi-threading: Almost all graphics computer game have to run on more than one thread. Typically, you need a thread to loop and render the graphics, and a thread to capture and handle the user input. For handling threads, you should use either Boost.Thread or the C++ standard thread library (if you have a recent-enough compiler, with C++0x support), but these two libraries are basically the same anyways. The important part in this topic is to learn to work with a program that does several things concurrently, which is not an easy thing in general.

2) File-handling: Any computer game will have to rely on several files and file-types. Whether it is simply some BMP files, or audio files, or some more complex 3D models and environments, and other custom files, you will have to deal with this. You have to learn to select appropriate formats, appropriate external libraries to handle them, and learn to interface between external libraries (learn to use the "PImpl" idiom to your advantage, make a clear separation (or firewall) between your code and external libraries). File-handling also requires not so trivial …

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

In the simplest possible way, it means:

Dear mister compiler,
In this place (or scope), I would like to be using this namespace that they call std . This would really help me because I won't have to qualify everything with std:: in the remainder of this scope.
Thank you.

And then, the compiler will do it. But, beware of the dangers of name-clashes if you abuse this feature.

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

Ho, yeah, you need to have the getVehicleType function also declared in the base-class such that it is accessible. You need to make it virtual such that it can be overriden in the derived class. Change your Vehicle class to:

// Vehicle: Vehicle number, type, capacity, driver assigned
class Vehicle{
  int id;
  public:
    //notice the addition of the ampersand (&) to mark as pass-by-reference
    // notice the change of name too.
    Vehicle(int& aId) : id(aId) {
      cout <<"Vehicle created successfully" << endl;
      ++aId;
    }
    int getID() const { return id; }
    virtual void getVehicleType() { }; //notice the 'virtual' keyword here.	
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You will find the reference on std::map here.

A simple example that basically fits your problem is this:

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main() {
  map<string,string> tags;
  //create the list of tags:
  tags["-color"] = "c";
  tags["-weight"] = "w";
  tags["-size"] = "s";
  //...

  while(true) {
    string input_tag;
    cout << "Please enter a tag (q for quit): ";
    cin >> input_tag;
    if(input_tag == "q")
      return 0;
    cout << "The tag '" << input_tag << "' corresponds to '" << tags[input_tag] << endl;
  };
  return 0;
};

Enjoy!

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

Well, first, your error about printing the object's content is easily solved. Your function "getVehicleType" prints the values already, so you just need to call it, don't insert it into a << operator statement, just call it:

//cout <<"id "<< vehicles[i]->getVehicleType() <<endl; //ERROR!
  vehicles[i]->getVehicleType(); //OK!

Now, about the ID, that's a bigger problem. You have many mistakes related to it:

First, you don't initialize your "id" variable in the main function. So, the id for the first Vehicle will be garbage anyways. You need to know that unless you give initial values to variables, they are created with any value (usually whatever garbage bits where set to before).

Second, in your Vehicle constructor, you have a data member with the same name as a parameter to the constructor. This is weird and ambiguous, and your compiler should at least warn you not to do this, because statements like id++; are not very clear (are you incrementing that data member or the parameter?). Make your life easier and pick a different name for your parameter.

Third, I don't know if you expected the value of the "id" variable in your main function to actually get incremented as Vehicles are created, but that is not going to be the case. When you send a variable to a function, it gets copied (pass-by-value) and any modification to the value of the parameter which is done within the function will not affect the variable that was passed to the function. …

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

First, you need to include <string> at the top, like I mentioned in the previous post. And this is what causes the error.

Second, you cannot allocate the array of strings before you know the size of the array.

Third, you should always prefer to declare variables where they are first used. This will help catch mistakes like I just mentioned (if "items" doesn't exist yet, you don't run into the danger of using it before it has been initialised).

Finally, you need to match every new statement with a delete statement when you are done with the array (that is what the compilation warning is about).

Correct indentation is also a big help for you and us.

So, with those small modifications, you get:

#include <iostream>
#include <iomanip>
#include <string> //include <string> in order to use the std::string class.

using namespace std;

int main()
{
  
  do //The do-while for a program rerun option
  {
    
    // Input information
    int items = 0;
    cout<<"How many sales items do you have? :";
    cin>>items;
	
    // Input and storage of items
    string* names = new (nothrow) string[items];
    if (names == 0) {
      cout << "Error: could not allocate the names array!" << endl;
      return 2; //terminate because you cannot recover from this problem.
    };

    double* price = new (nothrow) double[items];
    if (price == 0) {
      cout << "Error: could not allocate the price array!" << endl;
      return 1; //terminate because you cannot recover from this problem.
    };

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

You have two choices, 1) you create a second array of std::string on the side and populate and print it pretty much the same way as you do with the "prices" array, or 2) you create a structure that contains both a price and a name, and create an array of that instead of the two separate ones.

In the first option, you can simply create an array of std::strings (#include <string> at the top), and do this where you allocate the price array:

string* names = new string[items];

And then, input the names like so:

cout << "Enter the name of the sales item " << count + 1 << ": ";
      cin >> names[count];
      cout << "Enter the value of '" << names[count] << "': $";
      //.. as before

And similarly for printing it at the end.

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

>>I don't get why that's called static polymorphism?

Static: A mechanism which occurs at compilation or linking time.

Polymorphism: A programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function.

The example I showed fits perfectly into that definition, and this is why it is called static polymorphism.

>>All that's doing is generating multiple function for each type. There is nothing polymorphic about it.

Yeah, so what. There are, obviously, many other things that can be done in generic programming as well. But anyways, what about dynamic polymorphism? All it does is look-up a function pointer in a table, "there is nothing polymorphic about it". Polymorphism is an abstract concept, the implementation details involved in realizing it don't matter. It's the design perspectives that matter.

>> Polymorphism is more like a 1->many relationships, while that's like 1->1 relationship, that is each type has its own function.

You are right and wrong. To the compiler, it is just one function for each type, but this is after the fact, because it is done at compile-time, so, once compiled, the code is not "polymorphic" in the (1 -> many) kind-of way. But, once compiled, the polymorphism has already been realized. If you take the case of …

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

I can only give you an example in C++, because, to my knowledge, you cannot do compile-time polymorphism in Java. (and anyways, such a question belongs in the Java forum)

This is dynamic polymorphism in C++:

#include <iostream>

struct Animal {
  virtual void doCry() = 0;
};

struct Dog : Animal {
  void doCry() {
    std::cout << "Woof Woof!" << std::endl;
  };
};

struct Cat : Animal {
  void doCry() {
    std::cout << "Miaou.." << std::endl;
  };
};

void makeAnimalCry(Animal& a) {
  a.doCry(); // this call will be dispatched (at run-time) to the correct implementation.
};

int main() {
  Dog d;
  makeAnimalCry(d);
  Cat c;
  makeAnimalCry(c);
  return 0;
};

This is static polymorphism in C++:

#include <iostream>

struct Dog {
  void doCry() {
    std::cout << "Woof Woof!" << std::endl;
  };
};

struct Cat {
  void doCry() {
    std::cout << "Miaou.." << std::endl;
  };
};

// this function will be generated, at compile-time, for the given type of animal.
template <typename Animal>
void makeAnimalCry(Animal& a) {
  a.doCry(); //since this is generated at compile-time, no dispatch is needed, this is simple a normal function call (and possibly inlined as well, which is not possible in general in the dynamic case).
};

int main() {
  Dog d;
  makeAnimalCry(d);
  Cat c;
  makeAnimalCry(c);
  return 0;
};

Java is a language with JIT (Just-In-Time) compilation, so it is hard to distinguish compile-time mechanisms from run-time mechanisms, because it runs and compiles at the same time. And the JIT compiler can probably resolve some polymorphic …

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

Or maybe something along the lines of:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
  ifstream infile("input.txt");
  ofstream outfile("output.txt");
  int value;
  while(infile >> value) {
    char mod_val = (--value) % 52;
    outfile << string(value / 52 + 1, 
                      (mod_val < 26 ? mod_val + 'a' : (mod_val - 26) + 'A')) 
            << endl;
  };
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To store the prices as doubles, just make them doubles.

Declare your price pointer as:

double * price;

And allocate an array of doubles:

price= new double[items];

You don't have to change anything else (that I can see).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
$ sudo apt-get install linux-source

From a Linux terminal, of course.

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

>>then the class Diffusion Term can use all the members of Euqation. But, class Euqation can not use class diffusion.

NO. I mean that you should figure out what the Equation class needs the "DiffusionTerm" class for and create a base class which has those functions that Equation needs as a pure virtual functions, then you derive your DiffusionTerm class from that base class.

To continue on the example I had previously (with classes A and B), you could do this instead of using the circular dependency:

In C.h:

#ifndef C_H
#define C_H

class C {
  public:
    virtual void foo() = 0; //make the function that B needs as a pure virtual function in base class C. 
    virtual ~C() { };
};

#endif

In A.h:

#ifndef A_H
#define A_H

#include "C.h"

//class B; //no need to forward-declare class B. Instead, include B.h:
#include "B.h"

class A : public C {
  public:
    void foo() { //override foo() function.
      //..
    };  
    void bar(B* ptr) {
      ptr->foo(this);
    };
};

#endif

In B.h:

#ifndef B_H
#define B_H

//class A; //no need to forward-declare class A. Instead, use base class C.
#include "C.h"

class B {
  public:
    void foo(C* ptr) {
      ptr->foo();
    };
};

#endif

See how the circular dependency can be replaced by a common dependency on a base class (A depends on C because it inherits from it and implements its interface, and B depends on C to provide the interface it needs).

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

You need to be consistent with the const-qualifier, either you have a const function that returns a const reference or you have a non-const function that return a non-const reference, but usually, you can just do both:

const vector<double>& getDensity() const {return density;}
    vector<double>& getDensity() {return density;}

The compiler will select the correct overload depending on the const-ness of the object the "getDensity" function is called with.

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

A forward-declaration simply announces that a class with that name will be declared later. But to be able to use any of the members of the class (including constructor/destructor or any data members or member functions), the compiler has to have seen the declaration of the class, not just its forward-declaration. So, to allow this circular dependency to work, you have to interleave the declarations and the implementations. You can do this by separating the implementation and declaration, and inserting the inclusion of the required header in between them. This is usually accomplished as so:

In A.h:

#ifndef A_H
#define A_H

class B; //forward-declare class B.

class A {
  public:
    void foo();
    void bar(B* ptr); //declare-only the member function.
};

#endif

In B.h:

#ifndef B_H
#define B_H

class A; //forward-declare class A.

class B {
  public:
    void foo(A* ptr);
};

#endif

In A.cpp:

#include "A.h"   //include the header for the A class.
#include "B.h"   //include the header for the B class's definition.

void A::foo() {
  //..
};

void A::bar(B* ptr) {
  ptr->foo(this);  //now, the compiler has seen the declaration of B, so its member function can be used.
};

In B.cpp:

#include "B.h"
#include "A.h"

void B::foo(A* ptr) {
  ptr->foo();
};

The above will work. If you try to put the definition (or implementation) of the member functions in the header file (within the declaration) the compiler has no way to know what members the forward-declared class has, so how could it compile? Any member …

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

add the serialization library to the linking, directly. Not just under library directories, but also as a library to be linked. Find the boost_serialization library (either libboost_serialization_..a or boost_serialization...lib).

Boost has some automatic linking of some required libraries, but this system only works for some compilers (e.g. MSVC) but not for others (e.g. GCC). So, the code might automatically get the required library when compiled under one compiler, but it will not do that on another, in which case you have specify, manually, the libraries to be linked, this is the case for GCC (including MinGW/Cygwin).

When asking such a question, you should always specify the operating system, the compiler, and the build system (IDE), and any relevant compilation options.

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

>>How can I be a programmer who can understand the codes and writes neat and clean code.

You learn by experience, like anything else, practice makes perfect. If you are comfortable with the syntax of a language and the general logic of programming, then the next step is usually to start getting outside textbook examples, outside the comfortable world of standard libraries, outside your comfort zone. I mean, start writing projects that are complex enough (for you) that they require building a non-trivial software architecture (requires some thought into the design), that they require doing things you have never done and don't know how to do, and that they require using external libraries for doing things you can't or don't want to do yourself (like loading some file-formats (images, databases, etc.), or interfacing with some system, making a GUI, or using peripherals). Pick something you like, nobody can tell you what that is.

You learn to _understand_ code (other than your own) by being exposed to other people's code or to the interface or design of existing libraries. Be curious, and take it one step at a time (i.e. don't start by digging into Boost.Proto or some other crazy complicated library like that, start by looking at libraries that are small and simple enough that you could possibly be able to do it yourself, if you wanted to).

You learn to write _neat_ code as you make mistakes (that you won't want to repeat) and as you …

jonsca commented: Great info, Mike +14
Ketsuekiame commented: Perfect answer +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You don't need those #defines for linux and windows. There are a number of "standard" preprocessor defines which can tell you for what OS and compiler the code is being compiled for/with, in addition to a lot of other things (like C++0x support, multi-threading stuff, etc.). Here is a list for discriminating between the OS.

For example, you could just do:

int realmain() {
  //real work for the program goes here
}

#ifdef _WIN32
int WINAPI WinMain(
  HINSTANCE hInstance, 
  HINSTANCE hPrevInstance, 
  LPWSTR lpCmdLine, 
  int nShowCmd 
) {
#else
int main() {
#endif
  return realmain();
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your last post is completely incoherent. I would suggest you describe one problem, and provide all the code related to it, and do so coherently.

If profile.GetKeyPressed() works, it means that "profile" is declared incorrectly, so the declaration of it is the relevant code.

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

>> Maybe someone else can shed some light on the reason for needing this?
Just ask wikipedia. It's just an obscure Microsoft thing.

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

I believe that the difference is that Windows actually makes a difference between programs that run as a console application (MSDOS) and programs that run in the Windows system (Win32). If you try to run a program that uses WinMain() from a console window, you will probably get the message "This program cannot run in console." (at least, on older versions of windows that still had a native MSDOS environment available, newer versions only emulate the MSDOS environment via the "command prompt"). In Linux, and other *nix environments, all programs run in the terminal (whether you see it or not), and the GUI environment is nothing more than an external library invoked by the program.

But I might be wrong, it has been a while since I implemented any GUI app for windows, but I don't remember ever doing it without a WinMain function as entry-point. Also note that many cross-platform GUI libraries will hide away the entry-point function and provide you with a secondary function that acts as the entry-point for your purposes (which is usually invoked after the basic setup of the GUI application have been done).

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

Well, you are going to need to do simple input/output with the user and with a file.

For user input/output on the console, you will need <iostream>, with cout for output and cin for input. See this tutorial.

Then, you will need to use std::string to manipulate strings, to be able to write some text to be typed, and capture the text that was typed. Then you will need to be able to compare the strings (output and input) to figure out the success-rate, that's probably going to involve looping through the characters of the strings and comparing them.

Finally, you will need to use functions from the <ctime> header to time the user-input.

Do each of these things one at a time, and you will be in great shape.

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

You need to #include <string>. The problem is because iostream declares the string class via some inclusions under-the-hood, but it does not include the << operator for the string. At least, on some implementations, this is what happens, on others, it includes both the string class and its << operator, and thus, making the code work just fine. So, if you use the string class, always #include <string>, even if you think it is not needed (because of secondary inclusions), or even if it happens to work without.

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

The operation:

if(prompt2 == "ADD", "ADDITION", "+", "PLUS")

will not do what you expect. It will always evaluate to true, regardless of the value of prompt2. This is because it uses the comma operator. The comma operator has the effect of evaluating each elements between commas and return the value of the last element. In this case, it will evaluate the equality, then it will evaluate each string literal "ADDITION" "+" and "PLUS", and it will return the value of "PLUS" which is a pointer to char (C-style string) which will not be NULL, and thus, will be "true" as a conditional.

If you want to test that prompt2 is equal to any of those strings, you need to do:

if(prompt2 == "ADD" ||
   prompt2 == "ADDITION" ||
   prompt2 == "+" ||
   prompt2 == "PLUS")

If you have C++0x support for std::initializer_list, you can also define a simple function like:

template <typename T>
bool is_in_set(const std::initializer_list<T>& L, const T& value) {
  return std::count(L.begin(), L.end(), value) != 0;
};

//then, you can have the conditional:
  if( is_in_set({"ADD","ADDITION","+","PLUS"}, prompt2) )

But that is a bit more advanced, better stick to the traditional way given previously.

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

In the profiles.h, you declare the class CProfiles, of course, and the function to get the global instance, as so:

CProfiles& profile();

And, you access the instance through the profile() function everywhere you need it, but always through the function.

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

You have fell pray to the "static initialization order fiasco". Read the linked article, and you will understand the problem and read about the solution.

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

The recent C++ standard library provides both a std::map class and a std::unordered_map class. The former implements a binary search tree which gives you a list that is sorted by key values, with O(logN) lookup time. The latter implements a hashtable which does not give you a sorted list, but O(1) lookup time (or almost O(1), because of collisions). Both are used almost the same way.

With std::map:

#include <map>
#include <iostream>
#include <string>

using namespace std;

int main() {
  string english_word, french_word;
  map<string,string> dictionary;
  cout << "Enter English word (or 'q' to quit): ";
  cin >> english_word;
  while(english_word != "q") {
    cout << "Enter French word: ";
    cin >> french_word;
    dictionary[english_word] = french_word;
    cout << "Enter English word (or 'q' to quit): ";
    cin >> english_word;
  };
  cout << "Dictionary is: " << endl;
  for(map<string,string>::const_iterator it = dictionary.begin();
      it != dictionary.end(); ++it)
    cout << it->first << " " << it->second << endl;
  cout << "Enter a query English word (or 'q' to quit): ";
  cin >> english_word;
  while(english_word != "q") {
    cout << "The French translation of '" << english_word
         << "' is '" << dictionary[english_word] << "'." << endl;
    cout << "Enter a query English word (or 'q' to quit): ";
    cin >> english_word;
  };
  return 0;
};

With std::unordered_map:

#include <unordered_map>
#include <iostream>
#include <string>

using namespace std;

int main() {
  string english_word, french_word;
  unordered_map<string,string> dictionary;
  cout << "Enter English word (or 'q' to quit): ";
  cin >> english_word;
  while(english_word != "q") {
    cout …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I do agree that C and C++ are two distinct languages and, in general, you can just learn one (C++) directly. It's not like C is a stepping stone to learning C++. If you want to learn C++, then you don't need to learn C first, that's just a waste of time.

However, most books and courses will teach some aspects that are more commonly encountered in C (for a lack of a better, standard option), as a way to help understand the "low-level issues", which can be good only if you are doing fairly low-level programming in C++ too. Generally, I think it is also good to have some comparative knowledge of C/C++, mostly to understand why C++ standard libraries a generally considered better (but that's something to pick up along the way, it doesn't require that you pick up a C programming textbook).

Also, because C and C++ are very interoperable, and because C standard libraries are also part of C++ standard libraries, it can certainly come in handy to have some practical knowledge of C. I mean, libraries which are a mix of C and C++ source file are common-place in many settings. And some environments are restricted to C, or at least, to C standard libraries.

Knowing C is certainly an asset in some practical settings, but it's not a requirement for learning C++, and if you are going to learn some C before you get into learning C++, don't spend to much …

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

Is it "stack<int>" or an array? Because stack<int> is a standard container (adaptor), named std::stack. It is very possible that the author sloppily said it is an array, because many C++ programmers (including myself) will often forget that the general term "array" (which can mean any kind of homogeneous data-set) is sometimes directly associated with old C-style arrays (as in int[10] or a dynamic one). C++ programmers can often forget this because C-style arrays are so rarely used. So, it is possible that the author used the general term "array" without necessarily meaning a C-style array.

In this case, the only real mistake is that the function should return something, like an integer:

int sumStack(stack<int> istack)

And, yes, if the above is the code involved (and stack<int> is the standard implementation), then the original stack is left unchanged because it is passed-by-value (and thus, the function has its own internal copy of the stack, that can safely be emptied).

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

>>"to use a hash table to sort"

I'm not an expert on hashing, but this statement seems to make little sense to me. Hash tables are rarely used to sort anything (which requires a hash function that respects the ordering of the keys, which typically makes it very difficult to also make the hash function respect the distribution of keys (especially word-keys)). Overall, there will be so many collisions (or too many buckets) that it won't be worth it. Use a std::map or std::set instead. Since you want to map English words to French words, I suggest you use std::map<std::string, std::string>. Like so, for example:

#include <map>
#include <fstream>
#include <string>

int main() {
  std::map< std::string, std::string > dictionary;
  std::ifstream inFile("input.txt");
  std::string temp;
  while((inFile >> temp) && 
        (inFile >> dictionary[temp]))
    ;
  //.. then output as you wish, 'dictionary' now holds a sorted list of word-pairs.
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think that the first thing to do is to get a container for all the unique words that describe numbers (not compounded). If in English, that's not very hard or very many. The unique numbers run from 0 to 19, then 20-30-40..90 and 100-1000-1000000.., everything else is a compounded of these unique words. I would suggest you use a std::map<int, std::string> to store the associations of the numbers with the corresponding word, but only for those unique numbers. As so:

#include <map>

int main() {
  std::map<int, std::string> num_words;
  num_words[0] = "zero";
  num_words[1] = "one";
  num_words[2] = "two";
  ...
  num_words[19] = "nineteen";
  num_words[20] = "twenty";
  num_words[30] = "thirty";
  ...
  num_words[90] = "ninety";
  num_words[100] = "hundred";
  num_words[1000] = "thousand";
  num_words[1000000] = "million";
  num_words[1000000000] = "billion";
  ....

};

At this point, you can devise grammar rules to compound those number-words to construct any given number (up to some maximum). The first rule could be:

cout<<"ENTER NUMBER";
  cin>>number;

  if( number < 21 ) 
    cout << num_words[number]; //all numbers from 0 to 20 are not compounded.
  else if( number < 100 ) {
    cout << num_words[ (number / 10) * 10 ]; //extract the ten-multiple.
    if( number % 10 != 0 )
      cout << "-" << num_words[ number % 10 ]; //extract the last digit (1 to 9).
  } else ....
  //... so on for more complicated rules.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>im sure its a variable error in the compiler so any help on that?

And I'm sure your wrong. The compiler is never the problem (at least, extremely rarely, and only when doing really advanced stuff). Post more of the code, and implement the fix we suggested, then post the error messages that you get.

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

In your CManager class, you should have a data member like:

std::vector<CWorker> m_Workers;

In your CWorker, as suggested, you should have a constructor like:

class CWorker {
  //...
  public:
    CWorker(const char* aName,int aSalary = 0) {
      m_wName = aName;
      m_wSalary = aSalary;
    };

And, your addWorker function becomes:

void CManager::addWorker(const char *name,int salary)
{
  m_Workers.push_back(CWorker(name,salary));
}

And that's it. std::vector is much better and easier to use because it takes care of increasing and decreasing the capacity of your array such that you can add/remove elements very easily (and efficiently).

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

You have a semi-colon at the end of line 88, which should not be there. Because this is how the compiler interprets things:

void myFunction();     //declaration of "myFunction"

void myFunction()      //definition of "myFunction"
{
  //...
};

void myFunction();     //declaration of "myFunction"
{                      //ERROR: what is this { ? You cannot open a curly-brace in the middle of no-where.
  //...
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The error comes from lines 105 and 114, you should not multiply the numt by 3. The "count" given to the glDrawArrays is the number of vertices to draw, so it should be numt. As so:

glDrawArrays(GL_TRIANGLES, 0, numt);

Also, your class is missing several very important basic things, that is, the destructor (to delete vars, avoiding a leak), the copy-constructor and assignment operator (or disable them). Read my tutorial on that subject.

But, frankly, I would recommend you store your buffer "vars" using a std::vector<glVertexStructure>, it will be much easier to implement your "vertex" function correctly (although it is already correct).

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

The is a complete set of functions from WinAPI to "browse" the folders for the files. Personally, I think they are crap (annoying and kind-a hard to use). But, that is what the Open/Save file dialogs use in MFC or win32.

I would recommend you use Boost.FileSystem, it is much nicer (actually in C++), and is cross-platform.

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

In C++, we don't tend to use C style arrays, it is more common and easier to use standard classes that can hold arrays. In this case, you can use either std::vector<double> or, if you have a reasonably recent compiler, std::array<double,2>, as so:

#include <iostream>
#include <array>

using namespace std;

array<double,2> grav_force (double m1, double m2, const array<double,2>& r1, const array<double,2>& r2){
    // Calculate distance between bodies:
    double r12; // scalar distance
    array<double,2> r_12; // distance vector
    for (int i=0; i<2 ; i++){
        r12 += (r2[i] - r1[i])*(r2[i] - r1[i]);
        r_12[i] = r2[i] - r1[i];
    }
    r12 = sqrt(r12);
    // Gravitational factor:
    double G = m1*m2/(r12*r12*r12); // Grav.const. = 1
    return array<double,2>{ G*r_12[0], G*r_12[1] };
}

int main(int argc, char* argv[])
{
    array<double,2> r1 = {1.0, 2.0};
    array<double,2> r2 = {2.0, 4.0};
    double m1 = 1.0;
    double m2 = 1.0;
    array<double,2> asd = grav_force(m1, m2, r1, r2);
    cout << "asd: " << asd[0] << ", " << asd[1] << endl;

    return 0;
}

Or, better yet, you can use std::valarray which has most vector operations you would like:

#include <iostream>
#include <valarray>

using namespace std;

valarray<double> grav_force (double m1, double m2, const valarray<double>& r1, const valarray<double>& r2){
    // Calculate distance between bodies:
    valarray<double> r_12 = r2 - r1; // distance vector
    double r12 = sqrt((r_12 * r_12).sum()); // scalar distance
    // Gravitational factor:
    double G = m1*m2/(r12*r12*r12); // Grav.const. = 1
    return G * r_12;
}

int main(int argc, char* argv[])
{
    valarray<double> r1(2); r1[0] = …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This code:

myclass Object("some_file.xml");
if (Object.error_val == -1)
     delete Object;

Is invalid. You cannot "delete" things that are allocated on the stack. "delete" can only be used to delete things that were allocated with "new", as so:

myclass* Object = new myclass("some_file.xml");
if (Object->error_val == -1)
     delete Object;

Second thing is, you should throw an exception in the constructor if it was not successful. That's the best way to go. I would recommend that your function load_config throws an exception if the xml file cannot be loaded or is corrupt (not the correct format or the right data in it). In this case, you can do code like this:

try {
  myclass Object("some_file.xml");

  //use the Object, assuming it was correctly loaded (otherwise it would have thrown). 
  //...

} catch(cannot_load_xml_file& e) {
  // report error or do something alternative (backup solution).
};

Or, for dynamically allocated object:

try {
  std::auto_ptr<myclass> Object = std::auto_ptr<myclass>(new myclass()); //default constructor and automatic pointer (in C++0x, use std::unique_ptr, or std::shared_ptr).
  Object->load_config("some_file.xml");

  //use the object, assuming it was created and loaded successfully.
  //..

} catch(std::bad_alloc& e) {
  // report error about dynamic allocation failing to work.
} catch(cannot_load_xml_file& e) {
  // report error or do something alternative (backup solution).
};

Returning error codes or flags is an outdated method that is not recommended unless you are writing C code or writing functions that are exported from a DLL or .so file.

If you are serious about loading/saving object data to a file, …

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

Because the date in a "tm" structure is counted from year 1900. Which means that 2011 is stored as 111.

Generally, if you want to print a string from a time_t structure, use the function "ctime". Or, to convert from "tm" structure, use "asctime" or "strftime" for special formatting.

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

@tkud: What you are describing is what I call "derived class intersection", which is a very classic misunderstanding of what base classes are useful for. I suggest you revisit your understanding of the topic. Learn from the saying "Inherit not to reuse, but to be reused".

@tiredoy: The main purpose of base classes is to allow substitution of derived class objects for base class objects. If you develop an algorithm or data structure of some kind, you generally require that the input has some data and methods, generally called "requirements" which can be regrouped into "abstractions", which in OOP, are realized as base classes. The idea is that you develop the algorithm or methods to work using only what the abstraction provides (data and polymorphic functions). Then, any derived class (or implementation of the abstraction) can be reused by any of the methods that work on the base class. In other words, you can substitute, in the algorithms, objects of derived classes to act in the place of where the algorithms only require an object of the base class, and by this substitution, you can also inject code that modifies (or extends) the behavior of the algorithms. This is polymorphism.

"Compose to reuse"
"Inherit to be reused"

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

To give a more useful answer, that is, knowing what typically could happen when you delete a pointer twice might help you recognize the situation if you see those symptoms.

So, although it is undefined behaviour, as arkoenig mentioned, there are a number of things that would typically happen if you delete a pointer a second time, but it is, of course dependent on the implementation and the circumstances:
1) Nothing at all. It goes unnoticed and doesn't have a visible effect.
2) Heap corruption. The heap is asked to free a chunk of memory that is already freed or already allocated to something else, and because the heap is essentially a data-structure that does book-keeping of the free and allocated memory chunks, but at the same time, the heap typically cannot bare to do too much verification of the integrity of the requested allocation/deallocation, the result of deleting a pointer a second time can easily result in the heap being corrupted (i.e. it screws up the heap's book-keeping).
3) Crash. If the heap can verify that the pointer is already freed, or if the pointer happens to now be pointing outside the virtual address space of the program, the program will crash on either an access violation (seg. fault) or just a plain "abnormal termination".

If you see these symptoms or alternation between them (like changing something small in the code makes you jump from one symptom to the other), then you can suspect …

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

No. The best algorithm is to check that all off-diagonal terms are equal (within a tolerance). And, there are (N^2 - N) / 2 checks to be done, which is of order O(n^2).

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

The extra 0 in sort2.txt is caused by this line:

amountRead++; //what is this?

in the sort() function, and thus the "What is this?" comment that I made.

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

>>"The Beginners guide to C++" by Oleg Yaroshenko WROX press ltd 1994.

Get something that is more up-to-date. This book predates the first C++ standard (1998). Prefer a book that is post-2003. Here are recommendations.