m4ster_r0shi 142 Posting Whiz in Training

To check whether the file exists or not, you can try opening it for input and see if it's open. If it's
not open, it means it doesn't exist. If it doesn't exist, opening it for output will automatically create it.

Here's some pseudocode:

open file for input (use an ifstream object)

check if the file is open using the is_open member function

if (the file is open) everything is fine

else 
{
    open the file for output (using an ofstream object)
    output a big value to the file (e.g. 10000),
    which will be the default high score
}
m4ster_r0shi 142 Posting Whiz in Training

Your program doesn't remove anything :P It just outputs the string omitting the first letter.
E.g., entering this -> aaabbbddccc will cause your program to output this -> aabbbddccc

Can you describe in english how you would remove duplicates from a string?

If I give you this string -> aaabbbddccc# and tell you that you can only access two consecutive letters at a time
and the only thing you can do after you see the letters is decide to either print or not print a letter, what will you do?

m4ster_r0shi 142 Posting Whiz in Training

It works for me. At least on the easy level. Are you sure the file exists?

Another thing. I noticed that if the old score has more digits than the new one,
some of the old digits remain to the file. To take care of this, use different objects
for reading and writing from/to the file. If I were you, I would create two functions:

//...

double read_score()
{
    double score;

    ifstream fin("score.txt");

    fin >> score;

    fin.close();

    return score;
}

void write_score(double score)
{
    // opening for output erases 
    // the contents of the file

    ofstream fout("score.txt");

    fout << score << endl;

    fout.close();
}

//...

double old_score = read_score();

//...

double new_score = //...
write_score(new_score);

//...
m4ster_r0shi 142 Posting Whiz in Training
//...

if(n1 < n2)
{
    cout << "You beat the high score of " << n1 << "." << endl;
    
    file.seekp(0, ios::beg); // move to the beginning of the file before writing
    file << n2 << endl; // I believe you want to write the new high score
}

//...
m4ster_r0shi 142 Posting Whiz in Training

How can it use the function implicitly but not explicitly.

It can because the choice of the function to call isn't taken during compilation but while the program
is executed. Take a look at this here to see how -> http://en.wikipedia.org/wiki/Virtual_method_table

Also, note that this works ok:

//...

int main()
{
    derived d, *dp;

    dp = &d;
    dp->out();
    dp->base::out();

    return 0;
}
m4ster_r0shi 142 Posting Whiz in Training

when the base pointer points to derived object it prints i am derived

This is exactly what it's supposed to do.

Take a look at this:

#include <iostream>
#include <vector>
using namespace std;

struct Fruit
{
    virtual void Speak() {}
    virtual ~Fruit() {}
};

struct Apple : Fruit
{
    void Speak()
    {
        cout << "Hi! I'm an apple!\n" << endl;
    }
};

struct Pear : Fruit
{
    void Speak()
    {
        cout << "Hi! I'm a pear!\n" << endl;
    }
};

struct AnnoyingOrange : Fruit
{
    void Speak()
    {
        cout << "( http://www.youtube.com/user/realannoyingorange )\n";
        cout << "Hey Cabbage, know why you're so smart?\n";
        cout << "'Cause you have a big head. :D\n" << endl;
    }
};

template <class T>
void cleanup(vector<T*> v)
{
    for (unsigned i=0; i<v.size(); i++) delete v[i];
}

int main()
{
    vector<Fruit*> fruits;

    fruits.push_back(new Apple);
    fruits.push_back(new Pear);
    fruits.push_back(new AnnoyingOrange);

    fruits[0]->Speak();
    fruits[1]->Speak();
    fruits[2]->Speak();

    cleanup(fruits);

    cout << "hit enter to quit..." << endl;
    cin.get();
    return 0;
}

Also, take a look at this -> http://cplusplus.com/doc/tutorial/polymorphism/

m4ster_r0shi 142 Posting Whiz in Training

Ok. First, just to verify that this is where the problem comes from, try commenting out delete m_temp1; and delete m_temp2; and see what happens. Then, if these
two are indeed the cause of the problem, it would help a lot if you showed us the parts
of the code that involve m_temp1 , m_temp2 , m_HOBuffer and m_pBuffer .

m4ster_r0shi 142 Posting Whiz in Training

You mean CString::GetBuffer and CString::ReleaseBuffer ? I just checked the documentation on msdn...
(http://msdn.microsoft.com/en-us/library/aa314880%28v=vs.60%29.aspx, http://msdn.microsoft.com/en-us/library/aa300574%28v=vs.60%29.aspx)

...and it looks like you don't have to delete anything when you use CString::GetBuffer .

The buffer memory will be freed automatically when the CString object is destroyed.

So, if you delete[] memory you got with CString::GetBuffer , don't do it.

Also, note that CString::ReleaseBuffer does not deallocate the internal string buffer.

Use ReleaseBuffer to end use of a buffer allocated by GetBuffer.

m4ster_r0shi 142 Posting Whiz in Training

My best guess is that you delete[] memory that wasn't reserved with new[] .

Do the constructors of temp1 / temp2 set m_HOBuffer / m_pFileBuffer to zero?

Also, careful here:

temp2::~temp2()
{
    if (INFile.is_open())
        INFile.close();
    if (m_pBuffer) // either this should be m_pFileBuffer
        delete []m_pFileBuffer; // or this should be m_pBuffer
}
m4ster_r0shi 142 Posting Whiz in Training

Can you please explain why is this working?

Why shouldn't it work? I do it all the time :P In this case, the definition acts as a declaration too.

if I take of the friend from infront of the method name, it fails compiling

Well, operator << is a binary operator. This means it must take exactly two arguments. If you remove the friend keyword, you
make this function a member function. Now, there is an extra argument, the object for which it is called, for a total of three.

Something like this would work fine:

ostream & operator >> (ostream & stream)
{
    return stream << this->c_str;
}

You could call it like this:

my_string<char> str;

str >> cout;

Note that you would have trouble if you wanted to do this the usual way.
That is, provide the declaration in your class and the definition outside.

See why here -> http://cplusplus.com/forum/general/45776/

EDIT: Ah, right... I forgot that Koenig lookup is necessary for this to work...

m4ster_r0shi 142 Posting Whiz in Training

What you need is called dynamic memory allocation:

#include <iostream>

using namespace std;

struct Node {};

int main()
{
    int num_n;

    cout << "Enter number of nodes:\n";
    cin >> num_n;

    // Allocate memory dynamically

    Node * my_nodes = new Node[num_n];

    for (int i=0; i<num_n; i++)
    {
        // Set values of members of Node here

        // my_nodes[i] = ...
    }

    // Release memory when done

    delete[] my_nodes;
}

You could also use a vector:

#include <iostream>
#include <vector>

using namespace std;

struct Node {};

int main()
{
    int num_n;

    cout << "Enter number of nodes:\n";
    cin >> num_n;

    vector<Node> my_nodes(num_n);

    for (int i=0; i<num_n; i++)
    {
        // Set values of members of Node here

        // my_nodes[i] = ...
    }
}

Useful links:

http://cplusplus.com/doc/tutorial/dynamic/
http://cplusplus.com/search.do?q=vector

m4ster_r0shi 142 Posting Whiz in Training

Yes, in this case multithreading is the way to go. Well, since I have never used pthreads either (I'm a windows guy), I can't help you on this.

m4ster_r0shi 142 Posting Whiz in Training

How about something like this then?

SDL_event_handling_proc()
{
    get event;

    if (event == quit) quit;

    if (event == escape)
    {
        hide sdl window;

        show console

        bring console to foreground;

        call interpret_lua;

        hide console

        show sdl window;
    }
}

If you're on windows...

For showing/hiding the console window see this:
http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx

For bringing the console window to the foreground see this:
http://www.daniweb.com/software-development/cpp/threads/370728/1594255#post1594255

EDIT:

hmm a Quick Question if I have a loop(lets say loop1) and i have loop2 so loop2 is running inside loop1 does
loop1 actually continue looping or does it have to wait until loop2 is finished before starting its next iteration?

loop1 waits until loop2 is finished.

m4ster_r0shi 142 Posting Whiz in Training

If what you want is to make a GUI for a lua interpreter, I suggest handling all kind of input using SDL events.
Declare a buffer variable (char array or std::string) and when you get a keydown event modify it appropriately
(e.g. if a letter is pressed add it to the buffer, if backspace is pressed pop the last char from the buffer, etc...).
If the user hits enter, run the lua interpreter on your buffer.

m4ster_r0shi 142 Posting Whiz in Training

Well, are you really sure that the segafault is caused by the SDL
event handling procedure? What does your code look like now?

m4ster_r0shi 142 Posting Whiz in Training

There's a good tutorial on SDL here -> http://lazyfoo.net/SDL_tutorials/index.php

I modified some of the examples there, put them together and made this:

//The headers
#include <SDL/SDL.h>
#include <cstdio>

//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

SDL_Surface *screen = NULL;
SDL_Event event;

#undef main

int main()
{
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) return false;

    //Set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL ) return false;

    //Set the window caption
    SDL_WM_SetCaption( "event test", NULL );

    bool quit = false;

    while( !quit )
    {
        //If there is no event to handle, continue
        if ( !SDL_PollEvent( &event ) )
        {
            SDL_Delay(25);

            continue;
        }

        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;

            break;
            case SDL_KEYDOWN:
                printf("a key was pressed\n");

            break;
            case SDL_KEYUP:
                printf("a key was released\n");
        }

        SDL_Delay(25);
    }

    //Quit SDL
    SDL_Quit();
}

Does this work for you?

m4ster_r0shi 142 Posting Whiz in Training

As mentioned above, the main use of constructors is object initialization. You may think that this is not an important job, but
consider this -> You want to create a vector of 10 vectors of 10 ints and you want to assign the value 25 to all of them (the ints).

The manual way to do this would be:

vector<vector<int> > my_container;

my_container.resize(10);

for (int i = 0; i < 10; ++i)
{
    my_container[i].resize(10);
    
    for (int j = 0; j < 10; ++j)
        my_container[i][j] = 25;
}

Using constructors, you just have to write:

vector<vector<int> > my_container(10, vector<int>(10, 25));

Which one do you prefer?

However, this is not the only use of constructors. Another thing you
can do with them is impose limitations on the ways your objects can
be created. There are cases where you want to disable copying for
your objects (because, let's say, you don't want to share ownership of
a resource). A special kind of constructor, called the copy constructor,
is invoked when you create a new object from an existing one. If you
make this constructor private, you make your objects non-copyable
(well, you also have to make the assignment operator private).

A real world example are the ostream and istream classes. Try to make a copy of
cout -> ostream cout_copy(cout); or cin -> istream cin_copy(cin); You can't. And what does the compiler say? error: 'std::ios_base::ios_base(const std::ios_base&)' is private within …

m4ster_r0shi 142 Posting Whiz in Training

However, the challenge was more of a dismissal of the nonexistent problem rather than an actual challenge that needs to be answered.

Well, then I guess it doesn't make sense to keep it a secret any more...

#include <iostream>

int main()
{
    char ch;

    // one semicolon == one statement :P :D

    std::cin.rdbuf()->sputbackc('\0'),
    std::cin.get(ch);

    std::cout << "'" << ch << "' ("
        << (int)ch << ")" << std::endl;
}

that's typically only meaningful when it comes to user input from the keyboard

Then, comment out line 9 above and hit CTRL-Z (CTRL-D in unixes) and ENTER.

m4ster_r0shi 142 Posting Whiz in Training

I believe this means she is asking you to input a null into the input stream.

Exactly! But she doesn't say that this must be done using the keyboard.

m4ster_r0shi 142 Posting Whiz in Training

I would think that you cant exactly enter a NULL character.

Oh, I see. Well, I never said I can enter a NULL character using the keyboard.
Neither did Narue say that this was the challenge. Wait, I'll PM you the answer.

m4ster_r0shi 142 Posting Whiz in Training

A char that has an integer equivalent of 0 is an undefined character on output isn't it?

I don't know. When I output it as a single char, I get a space. However,
when I use it to mark the end of a string (0 == '\0'), nothing is printed.

m4ster_r0shi 142 Posting Whiz in Training

I challenge you to input a character with the value of 0 using cin. It's not as simple as you might think.

Assuming I have a char variable declared, I can do this in one statement.

m4ster_r0shi 142 Posting Whiz in Training

it due by tomorrow

Well, you'd better hurry and check out the links I gave you!

I'll give you one last hint:

cmplxNumber add_cmplx(const cmplxNumber & c1, const cmplxNumber & c2)
{
    // create a complex number variable (let's call it temp) 
    
    // set temp's real part to 
    // c1's real part plus c2's real part
    
    // set temp's imaginary part to 
    // c1's imaginary part plus c2's imaginary part
    
    // return temp;
}
m4ster_r0shi 142 Posting Whiz in Training

Hmmm... I'm really beginning to believe that the code you posted above is not yours...
Why don't you refresh your knowledge of functions and structures and then try again?

http://cplusplus.com/doc/tutorial/functions/
http://cplusplus.com/doc/tutorial/functions2/
http://cplusplus.com/doc/tutorial/structures/

m4ster_r0shi 142 Posting Whiz in Training

This means that you just declared your functions, i.e. you just added these lines to your code:

cmplxNumber add_cmplx(const cmplxNumber & c1, const cmplxNumber & c2);
cmplxNumber sub_cmplx(const cmplxNumber & c1, const cmplxNumber & c2);

You have to define them too (i.e. tell the compiler exactly how they work). Just like you do with PrintComplex.

This is its declaration:

ostream & PrintComplex( ostream & outDevice, cmplxNumber Root );

And this is its definition:

ostream & PrintComplex( ostream & outDevice, cmplxNumber Root )
{
	outDevice << Root.dReal;
	if( Root.dImaginary < 0.0 ) {
		outDevice << " - " << abs(Root.dImaginary) << " j" << endl;
	}
	else if( Root.dImaginary > 0.0 ) {
		outDevice << " + " << Root.dImaginary << " j" << endl; 
	}
	else 
		cout << endl;
	return outDevice;
}
m4ster_r0shi 142 Posting Whiz in Training

The problem is that your compiler doesn't know how to add/subtract complex numbers using operators +/-

A simple solution is to define two functions for these operations...

//...

cmplxNumber add_cmplx(const cmplxNumber & c1, const cmplxNumber & c2)
{
    //...
}

cmplxNumber sub_cmplx(const cmplxNumber & c1, const cmplxNumber & c2)
{
    //...
}

//...

...and then use them like this:

//...

C = add_cmplx(A, B);

//...

C = sub_cmplx(A, B);

//...
m4ster_r0shi 142 Posting Whiz in Training
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void shuffle(const string deck[52], string card[52])
{
    // build your temp array here

    for(int i = 0; i < 52; ++i)
        card[i] = deck[temp[i] - 1];
}

int main()
{
    string deck[52] = { "H*A","H*2","H*3","H*4","H*5","H*6","H*7","H*8","H*9","H*10","H*J","H*Q","H*K",
                        "D*A","D*2","D*3","D*4","D*5","D*6","D*7","D*8","D*9","D*10","D*J","D*Q","D*K",
                        "C A","C 2","C 3","C 4","C 5","C 6","C 7","C 8","C 9","C*10","C J","C Q","C K",
                        "S A","S 2","S 3","S 4","S 5","S 6","S 7","S 8","S 9","S*10","S J","S Q","S K"};
    string card[52];

    shuffle(deck, card);
}

EDIT: You could also put deck inside the function...

//...

void shuffle(string card[52])
{
    static const string deck[52] = { /*...*/ };

    // build your temp array here

    for(int i = 0; i < 52; ++i)
        card[i] = deck[temp[i] - 1];
}

int main()
{
    string card[52];

    shuffle(card);
}
m4ster_r0shi 142 Posting Whiz in Training

The fact that the function doesn't return anything is irrelevant here.
You can pass your array as an argument, modify it, and the changes
you make will be reflected in main. This is the default behaviour
for arrays. I assure you it will work if you fill in the missing code.
I have tried it and it works perfectly fine for me.

m4ster_r0shi 142 Posting Whiz in Training

i tried your code...

Which one?

This -> http://www.daniweb.com/software-development/cpp/threads/370601/1593577#post1593577 ?
Or this -> http://www.daniweb.com/software-development/cpp/threads/370601/1593600#post1593600 ?

The first obviously won't work unless you fill in the missing code (which is not too hard).
The second obviously won't work if you don't have the necessary boost headers.

m4ster_r0shi 142 Posting Whiz in Training

Ok, I'll play along.

#include <boost/shared_array.hpp>
#include <iostream>
#include <string>

boost::shared_array<std::string> test()
{
    boost::shared_array<std::string> array(new std::string[5]);

    array[0] = "Hello";
    array[1] = "World";
    array[2] = "How";
    array[3] = "Are";
    array[4] = "You";

    return array;
}

int main()
{
    boost::shared_array<std::string> b;

    b = test();

    for(int i = 0; i < 5; ++i)
        std::cout << b[i] << std::endl;

    return 0;
}

EDIT:

i want a function to do some modification to an string array and pass it back...

Did you see my first reply?

m4ster_r0shi 142 Posting Whiz in Training

Why don't you pass the array as an argument to the function instead?

//...

void test(string a[5])
{
    a[0] = "Hello";

    //...
}

int main()
{
    string b[5];

    test(b);

    //...
}
m4ster_r0shi 142 Posting Whiz in Training

You need to add const qualifiers in your function's declaration and definition.

//...

class csv_File
{
    //...

    void dump2ivector(int column, vector<int> &data) const;

    //...
};

//...

void csv_File::dump2ivector(int column, vector<int> &data) const { /*...*/ }

//...

EDIT: Too slow...

m4ster_r0shi 142 Posting Whiz in Training

Does grab return a reference?

m4ster_r0shi 142 Posting Whiz in Training

You shouldn't delete your buttons in your constructor. Do it in your destructor, using a for loop.

The for loop in your constructor should look like this:

//...

for(int bt_index = 0; bt_index < NrButtons; bt_index++)
{
    File >> mask; //rading the mask
    File >> imag; //normal image
    File >> imag1;//animated image
    File >> bt_position.x;
    File >> bt_position.y;

    tButton = new Button(imag1.c_str(), imag.c_str(), mask.c_str(), bt_position);
    this->v_button.push_back(tButton);
}

//...

In the constructor I push in the vector a pointer to where memory was allocated, but because I delete the memory allocated in the previous loop(line 72->76)
and set to NULL(and because the pointers in the vector have the same address, they will also point to NULL)such as only the last vector wasn't equal to NULL.

When you push_back a pointer in your vector, a new pointer (careful here, a new pointer, not a new button) is created
and set to point to the address tButton does. Setting tButton to NULL doesn't affect the pointer stored in your vector.

However, deleting tButton sends a message to your OS that that particular memory area is free
to be used by your OS or by other programs. This is bad because the pointers in your vector
point to that area too. The result of using the data in that memory area is undefined.

Since your program doesn't crash and you don't see your buttons, my guess is that either your buttons are drawn but
because …

m4ster_r0shi 142 Posting Whiz in Training

Obviously, we need to see the definition of DocProduction too.

Is CDocum's destructor virtual? If yes, I suspect that the
problem is caused by accidentally overwriting the vtable.

m4ster_r0shi 142 Posting Whiz in Training

Can you show us the definition of CDocum::~CDocum and CDocum::QuoteDocProd?

m4ster_r0shi 142 Posting Whiz in Training

Are you sure the file exists and is in the correct folder? What do you mean by saying they do not work?
Are you getting compilation errors, or is it something else? It would really help if you posted your code.

m4ster_r0shi 142 Posting Whiz in Training

I have a suspicion, I could be wrong though. Do you actually allocate memory for that event?

If you do this instead, does it work?

void proc_events()
{
    SDL_Event my_event;

    while( SDL_PollEvent( &my_event ) )
    {
        if ( my_event.type == SDL_QUIT )
            SDL_Quit();
    }
}
m4ster_r0shi 142 Posting Whiz in Training

It really isn't easy to say without seeing the contents of "user.hpp"...

If I were you, I'd put cout statements in key places of the code in order to isolate the problem.

m4ster_r0shi 142 Posting Whiz in Training

If you don't modify your initial vector after populating the second, I guess it's ok.
Otherwise, both approaches (pointers and iterators) are problematic.

BTW, there are ready solutions to this -> http://www.boost.org/doc/libs/1_46_1/libs/multi_index/doc/index.html

EDIT: Also, if you use decide to use pointers, you probably need pointers to myClass, not to int :P

m4ster_r0shi 142 Posting Whiz in Training

Err... What is if(argc==1) { cout<<"Either use the -l or -ls arguments\n"; } doing down there? It should be the first thing inside main. In fact, it should be like this:

int main(int argc, char ** argv)
{
    if(argc == 1)
    {
        cout << "Either use the -l or -ls arguments\n";

        cout << "(hit enter to quit...)"; cin.get();

        return 0; // terminate the program
    }

    //...
}

What exactly is the problem again? What do you expect the program to do? What does it do?

Celtrix commented: thanks man that saved me a lot of trouble. +2
m4ster_r0shi 142 Posting Whiz in Training

The test should be if(argc == 1) . argc always is at least 1, as the first argument always is the command that invoked the program.

m4ster_r0shi 142 Posting Whiz in Training

Yes, it's what I thought it is. Make the signature of your function -> void addPerson(Person * & head) and it should be ok.

The problem with void addPerson(Person * head) is that, while you can modify the data pointed to by head ,
you can't modify head itself. And you want to be able to modify head here (at least) -> head = newNode;

m4ster_r0shi 142 Posting Whiz in Training

I know I should pass it as a pointer, but for some reason it still doesn't seem to be doing anything.

How do you do this? Could you post an example? Mind that you may have to pass the pointer by reference (or by pointer). Check this out:

#include <iostream>

using namespace std;

void f1(int *   p) {  p = (int *) 0xff; }
void f2(int * & p) {  p = (int *) 0xff; }
void f3(int * * p) { *p = (int *) 0xff; }

int main()
{
    int * p1 = 0;
    int * p2 = 0;
    int * p3 = 0;

    cout << "p1 = " << p1 << endl;
    cout << "p2 = " << p2 << endl;
    cout << "p3 = " << p3 << endl;

    cout << "\ncalling f1, f2, f3..." << endl;

    f1(p1); f2(p2); f3(&p3);

    cout << "\np1 = " << p1 << endl;
    cout <<   "p2 = " << p2 << endl;
    cout <<   "p3 = " << p3 << endl;

    cout << "\n(hit enter to quit...)"; cin.get();

    return 0;
}
m4ster_r0shi 142 Posting Whiz in Training

Q1
The semicolon (;) just indicates the end of a statement. It has nothing to do with the end of the string.
When you use double quotes (") around text, your compiler kindly puts a null character at the end.

Q2
phrase is an array of 13 chars. This -> char phrase[] = "Game Over!!!"; is interpreted by the compiler as char phrase[13] = { 'G', 'a', 'm', 'e', ' ', 'O', 'v', 'e', 'r', '!', '!', '!', '\0' };

crapgarden commented: Very Helpful +3
m4ster_r0shi 142 Posting Whiz in Training

You can always use the C version of ostringstream -> http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/