Narue 5,707 Bad Cop Team Colleague

Technically it is cleaned up, unless you're on a platform that doesn't reclaim dynamic memory for a process when the process terminates. But if you mean the pointer is never deleted explicitly, that's easy enough. Just print something in the destructor, throw an unhandled exception, and watch the message never get printed:

#include <cstdlib>
#include <exception>
#include <iostream>

class SimpleException {
public:
    SimpleException() { std::cerr<<"Creating MyException object\n"; }
    ~SimpleException() { std::cerr<<"Destroying MyException object\n"; }
};

void unhandled_handler()
{
    std::cerr<<"Terminating due to unhandled exception\n";
    std::exit(EXIT_FAILURE);
}

#define CATCH_UNHANDLED 0 // Set to 1 to catch and delete

int main()
#if CATCH_UNHANDLED
try
#endif
{
    std::set_terminate(unhandled_handler);
    throw new SimpleException();
}
#if CATCH_UNHANDLED
catch (const SimpleException* pex) {
    delete pex;
}
#endif
iamthwee commented: No _jsw variables... This deserves +ve rep. +13
Narue 5,707 Bad Cop Team Colleague

>Is it just me, or do you find your patience stretched rather thin when posting here at Daniweb sometimes?
Sometimes? When the majority of questions are students looking for a handout, a constant state of zero patience is normal. Though I have infinite patience for people who are truly interested in bettering themselves and actually try to learn.

>A) People posting completely incorrect code/answers
There's nothing wrong with ignorance. Don't expect everyone to be perfect. Now if they continue to post the same things that are wrong, that's different. Willful ignorance is not cool.

>B) People agreeing with completely incorrect code/answers
Once again, there's nothing wrong with ignorance. A lot of people simply learn the wrong things. We should help them correct the misunderstandings, not berate them and allow them to remain ignorant.

>C) People telling me that my code is wrong/doesn't work when i know perfectly well that it does
While this happens to the best of us, most of the time the best response is to consider that your code actually is broken. If you can prove that it's correct, do so. If not, that's an indication that there's a problem. Despite what Larry Wall says, hubris has no place in programming.

>But is it just me that finds it infuriating having to defend your posts to
>people who clearly have no understanding of the point they are arguing?

I have no problem defending myself if I'm …

Geekitygeek commented: true, true and umm...true :) +0
Narue 5,707 Bad Cop Team Colleague

>So kindly hlp me out to decide it...
I fail to see how we can help. We know nothing about your knowledge or about you...except that you're exceedingly uncreative and generally clueless about what you've been studying for the last N years.

Narue 5,707 Bad Cop Team Colleague

Once link becomes a null pointer, you've left the realm of the tree. Assigning to link at that point does nothing productive. What you need to do is save a pointer to the last node before link become null, and then assign tmp to either the lc or rc link (depending on the direction you're moving) of that node:

#include<stdio.h>
#include<stdlib.h>

struct node {
    int data;
    struct node *lc;
    struct node *rc;
};

int main()
{
    struct node *start = NULL;
    int i,n,flag;

    printf("how many integers you wish to enter\n");
    scanf("%d",&n);

    for(i=0;i<n;i++) {
        struct node *tmp = malloc(sizeof(struct node));
        int a;

        scanf("%d",&a);

        tmp->data=a;
        tmp->lc=NULL;
        tmp->rc=NULL;
        flag=0;

        if (start==NULL)
            start=tmp;
        else {
            struct node *last = start;
            struct node *link = start;

            while (link!=NULL) {
                last = link;
                if (link->data==a) {
                    printf ("The element already exists");
                    flag=1;
                    break;
                }
                else if (a>link->data) {
                    link=link->rc;
                    printf("rc\n");
                }
                else if (a<link->data) {
                    link=link->lc;
                    printf("lc\n");
                }
            }

            if (flag==0) {
                if (a > last->data)
                    last->rc = tmp;
                else
                    last->lc = tmp;
            }
        }
    }

    return 0;
}
Narue 5,707 Bad Cop Team Colleague

>I just (wrongly) assumed that all compilers would compile simple increments the same
As with many compiler specifics, it's not quite that simple. Depending on the target processor, different instructions may be deemed more efficient. So you'll see compilers favoring for example add over inc, or lea over both add and inc. The bias can change even within the same processor family. So the machine code itself may vary depending on hardware targets.

In terms of which of ++x , x++ , x+=1 , and x=x+1 is faster, you're talking about one of the most basic of basic optimizations (even Ritchie's first C compiler did this). Much like I would expect local variable allocation along with the stack frame regardless of scope rather than when execution enters each scope, I would expect all of the above (in isolation) to produce identical instructions even with optimization disabled.

So let's look at the questions I saw pop up in the thread:

  • Q: Which is faster, ++x or x+=1 ?
    A: On any decent compiler there's no difference, but only when the expressions are taken in isolation. As part of a larger expression, there's more to consider. However, the usual guideline of "mind your own business and let the compiler handle micro-management of expressions" applies. It's better at it than you are anyway.
  • Q: Will the above compile to the same machine code on my compiler?
    A: It's very likely, unless you have a compiler that aggressively …
Narue 5,707 Bad Cop Team Colleague

>I can't figure out how to return a local variable.
There are two other common options aside from making the variable static:

  1. Pass in a buffer and work with it.
    char *time_stamp(char *buf, size_t size)
    {
        /* Populate buf */
    
        return buf;
    }
  2. Dynamically allocate the memory.
    char *time_stamp(void)
    {
        char *str = malloc(21);
    
        /* Populate str */
    
        return str;
    }

Just as with static, these options have advantages and disadvantages. It's really up to you to pick which one works best for your application. However, I'll mention that I usually pass in a buffer. That way the caller has more control over memory and things remain cleaner (if more verbose on the caller side).

Narue 5,707 Bad Cop Team Colleague

So I see, though you'll need to go about it less directly:

char *temp = time_stamp();
char *timeBegin = malloc(strlen(temp) + 1);

if (timeBegin == NULL) {
    /* Handle the error */
}

strcpy(timeBegin, temp);

Since the string returned by time_stamp is stored in a static array, you need to make a copy of the data before the next call to time_stamp.

[edit]
>with out haveing to make the local variable (in time_stamp()) static?
Now I'm confused. Is it static or not? That makes a huge difference in your program's correctness. Your first post says it's static and now you imply that it's not.
[/edit]

Narue 5,707 Bad Cop Team Colleague

flushall isn't guaranteed to be available as it's a non-standard extension. Besides, you can achieve the same effect as flushall (assuming it does what one might expect) with fflush(NULL).

Narue 5,707 Bad Cop Team Colleague

This is one area where arrays and dynamic arrays are different. To pass an actual array as a function parameter, the following syntax is used:

T (*param_name)[COLS]

Alternatively, you can use the empty dimension syntactic sugar:

T param_name[][COLS]

The first dimension can also hold a size, even though it's ignored:

T param_name[ROWS][COLS]

In real code it looks like this:

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <ostream>

template <typename T>
std::ostream& display(std::ostream& out, T (*array)[5], std::size_t n)
{
    for (std::size_t i = 0; i < n; i++) {
        for (std::size_t j = 0; j < n; j++)
            out<< std::setw(std::numeric_limits<T>::digits10 + 2) << array[i][j];
        out<< out.widen('\n');
    }

    return out;
}

int main()
{
    const int N = 5;

    int a[N][N];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            a[i][j] = rand();
    }

    display(std::cout, a, N);
}

The reason for this odd syntax is the rule that an array is converted to a pointer to the first element when used in value context (ie. int a[10] becomes int *a ). Passing an array to a function is value context, so the first dimension of a two-dimensional array "decays" into a pointer. But multi-dimensional arrays in C++ are not true multi-dimensional arrays. Rather, they're arrays of arrays. The difference is subtle, but the end result is that this pointer decay rule only applies to the first dimension of a multi-dimensional array, and an array of arrays of T …

Narue 5,707 Bad Cop Team Colleague

>Who make better programmers? Men or Women?
Based on my experience conducting interviews, I'd say men make better programmers on average. Of course, that's completely anecdotal with no scientific rigor, so it's worthless as an answer to your question. I'm not aware of any studies on the subject; you'll simply need to form your own opinion.

Narue 5,707 Bad Cop Team Colleague

>But I can't understand how p holds the value 30000 or how the result of the program is addition of 30000 and 20..
Presumably this hideous trick is meant to add two numbers without using the + operator. a is converted to a pointer to char, thus making the address pointed to by be 30000. Then the subscript operator is used to get to an object at an offset of b beyond the address pointed to by p. b is 20 and p+140==30020 (p is a pointer to char so that the step size is 1 rather than sizeof(int)). Use the address-of operator on the resulting object, convert the address back to int, and you've got the effect of a+b.

>What does the following statement declare: [ char *a[][40]; ]
Break it down from the inside out:

a       // a is an
       []     // array of undefined size of
         [40] // arrays of 40
     *        // pointers to
char          // char
Narue 5,707 Bad Cop Team Colleague

>NO, at least, it would be extremely surprising and weird. Just try and see. I
>bet you that if you have a proper compiler, it will issue a compilation error.

If your compiler complains about a pure virtual destructor, either the compiler is non-standard, or your code is wrong.

>Why? Well it does not make any sense[...]
You're mistaking "pure virtual" with "no definition". While there's a restriction that pure virtual functions cannot have an inline definition:

virtual void foo() = 0 {} // Illegal syntax

There's no provision against defining a pure virtual function. In fact, such a definition is required if the function is called implicitly (as in the case of destructors), or explicitly. One example of an explicit call is the base class providing a default implementation and the derived class using it:

class base {
public:
    virtual void foo() = 0;
    virtual ~base() {}
};

void base::foo() {}

class derived: public base {
public:
    void foo() { base::foo(); }
};

>Is there any concept of pure virtual destructor in C++?
Yes. As you should already know, base classes should generally have a virtual destructor. If you want the base class to be abstract (generally a good practice) but it doesn't have any pure virtual member functions, the destructor can be made pure. It's a convenient and common technique for making a base class abstract without unnecessarily forcing implementations in the derived class.

class base {
public:
    virtual ~base() …
Narue 5,707 Bad Cop Team Colleague

>How many years will it take one on avg to master C++ (doing self study) or atleast get a fair touch of this lang?
Mastery is quite different from competence (which is how I interpret "a fair touch"). If you're an experienced programmer you can become competent with C++ in less than a year. Proficiency suggests experience, and experience only comes from writing lots of code, reading lots of code, and studying the literature. So to become truly proficient in C++ I'd say 5+ years unless you have no life. ;)

As for mastery, I'd say it's impossible. C++ is an extremely robust language with not a few nuances, and it's constantly evolving both in the language proper and ways of using it. I think of mastery as knowing and having experience with everything there is to know.

Fbody commented: Agreed :) +2
Narue 5,707 Bad Cop Team Colleague

Hmm, I think it makes more sense for the adventurers to have their own list of usable abilities. That follows the more standard progression where new abilities can be learned, and it saves you the trouble of trying to determine which abilities are usable by which characters when there's no solid relationship between the two.

The details can certainly be ironed out more, but here's a rough idea of what I mean in the form of a basic battle system:

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <boost/shared_ptr.hpp>

class Actor;

class Ability {
    std::string _name;
public:
    Ability(const std::string& name): _name(name) {}
    const std::string& DisplayName() const { return _name; }
    virtual void Use(Actor& user, Actor& target) = 0;
};

class Actor {
    typedef boost::shared_ptr<Ability> AbilityPtr;
    typedef std::map<std::string, AbilityPtr> AbilityList;
private:
    std::string _name;
    int _health;
    int _attack;
    AbilityList _abilities;
public:
    Actor(const std::string& name, int attack)
        : _name(name), _health(30), _attack(attack)
    {}

    const std::string& Name() const { return _name; }
    int Health() const { return _health; }
    int AttackDamage() const { return _attack; }
    void AdjustHealth(int difference) { _health += difference; }

    bool HasAbility(const std::string& ability_name)
    {
        return _abilities.find(ability_name) != _abilities.end();
    }

    void AddAbility(Ability *ability)
    {
        if (!HasAbility(ability->DisplayName()))
            _abilities.insert(std::make_pair(ability->DisplayName(), AbilityPtr(ability)));
    }

    void UseAbility(Actor& target, const std::string& ability_name)
    {
        if (HasAbility(ability_name))
            _abilities[ability_name]->Use(*this, target);
    }
};

class PrimaryAttack: public Ability {
public:
    PrimaryAttack(): Ability("Primary Attack") {}

    virtual void Use(Actor& user, Actor& target)
    {
        bool crit = rand() < RAND_MAX / 10;
        int dmg = user.AttackDamage();

        if (crit)
            dmg …
Narue 5,707 Bad Cop Team Colleague

>if one has a lot of getters and setters, its usually a hint of bad design.
That works for me.

NicAx64 commented: agreed ! +2
Narue 5,707 Bad Cop Team Colleague

>Do you read the DaniWeb news stories?
No.

>If not ... what about them doesn't interest you?
There are better sites for news, in my opinion. I treat Daniweb as a forum, nothing more.

Narue 5,707 Bad Cop Team Colleague

>1) Explain why this is used - what are the pros/cons?
That's quite a broad question. Can you be more specific about what you learned and what part of it is confusing?

This is a tutorial that I wrote. It's more of an overview of pointers in general, but it might answer some of your questions.

Your_mum commented: put simply, that tut is all anyone will ever need for pointers :) +2
Narue 5,707 Bad Cop Team Colleague

Hi first you need to study operator precedence well. Here you are using ++ operator post fix and prefix. ++ directly charge the value in variable address.

post fix (a++)- print first and increment
prefix (++a)- increment first and print the value

printf("%a%a%a", a, ++a, a++);
                          1    //and then increment  a = 2;
printf("%a%a%a", a, ++a, a++);
                      3    1    //its prefix so increment a = 3 an print
printf("%a%a%a", a, ++a, a++);
                  3    3    1

end quote.

First you need to study side effects and sequence points. The snippet exhibits undefined behavior, which means that the output can be anything at all. Further, the output isn't even required to be consistent. You can run the program twice and completely different results should be expected with undefined behavior.

This thread has become a wealth of bad examples...

Ketsuekiame commented: Finally some sense in this thread. :D (Even if it is 5 years old) +1
Narue 5,707 Bad Cop Team Colleague

>no I DIDN'T read the rules
Then don't complain when you're punished for breaking the rules you didn't bother to read.

>cuz people who read the rules are for people who don't have their own website
So having your own website means you can break the rules on somebody else's website? I find your lack of logic unsurprising, yet impressive.

>and no money TO MAKE THEIR OWN RULES
You don't make the rules here, Dani does. You follow the rules or leave. If you don't like that, make a competing forum that embraces anarchy and good luck.

Lusiphur commented: Concise, to the point, says what everyone else was thinking. +0
Narue 5,707 Bad Cop Team Colleague

>Unfortunately I can't find where I can delete my account?
You can't delete your account. Just don't visit the site anymore. It's really that easy. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

I am trying to figure out the advantages of C++ STL containers over C.

C++ has STL containers and C doesn't. Case closed, Sherlock. I get the impression that you're building a fallacious argument about C++'s superiority over C, which is a complete waste of time because it lacks objectivity and useful conclusions. A far more enlightening comparison would be the support in each language for writing container libraries. But that involves a great deal more effort on your part in coming up with excellent examples for each language and compelling arguments for both sides. I have yet to see such a comparison, so if you can pull it off you'll have my respect.

Narue 5,707 Bad Cop Team Colleague

You should really reconsider relying on non-portable behavior (eg. fflush(stdin)) and non-portable functions (eg. gets_s) if you can avoid it. I'd also recommend merging your months into an array. Even if you waste a few elements of an array, it's still a win in complexity if you consider nothing more than the tedious C_Year::InitYear. Beyond that I'd just be nitpicking.

One thing I did wonder about while reading your code: why virtual destructors? You have no other virtual member functions, and unless you know for a fact that the types will be treated polymorphically down the road, why add the complexity?

Narue 5,707 Bad Cop Team Colleague

I'll take a look at it for you. You can find my email on my homepage, and my homepage on my Daniweb profile (giving spammers a harder time than simply posting it here).

Narue 5,707 Bad Cop Team Colleague

Prime_Finder findprimes();

You've independently discovered a rather subtle problem with C++'s grammar. This line is actually interpreted as a function declaration. The function is called findprimes, has no parameters, and returns and object of type Prime_Finder.

To define an object with the default constructor, omit the empty parens:

Prime_Finder findprimes;
Narue 5,707 Bad Cop Team Colleague

It's very rare when one absolutely needs to keep everything loaded at the same time. I'd recommend changing your logic so that you only need to keep a few records in memory at once.

Narue 5,707 Bad Cop Team Colleague

hi i would like u to tell me if i can make a random function to choose between four numbers and only them(-1 , 1 , -10 ,10)

Yes, you can. Quite easily, in fact:

int a[] = { -1, 1, -10, 10 };
int choice = a[rand() % 4];

rand(x) will always return a number from 0 to (x-1).

No, rand will always return an integer in the range of [0, RAND_MAX). rand doesn't take any parameters. On top of being overly complicated, your code is flat out wrong. Perhaps you were thinking of one of the many non-portable alternatives (not called rand) that compilers like to offer?

nbaztec commented: Thanks for correcting me. :) +1
Narue 5,707 Bad Cop Team Colleague

isn't it supposed to stop on 5 letters or at least don't memorize these plus letters?

Why would it? You never told it to do anything of the sort. In fact, it's quite impossible to include those safety measures with the gets function. You simply invoke undefined behavior, and the program is allowed to do anything (including behaving normally or crashing).

Now for some tips:

main(){

Two problems here.

  1. Implicit int has been removed in the latest C standard, which means eventually your code will fail to compile. You should be explicit:
    int main(void)
  2. Since you tried to use implicit int, you're clearly not compiling under the latest standard. Therefore, failure to return a value is also undefined behavior. It's generally considered best practice to return a value, even in C99:
    int main(void)
    {
      return 0; /* Standard "success" value */
    }
printf("dimension du tableau?");

If you want the prompt to show up before blocking for input, either print a newline or flush the output stream. Since printing a newline isn't acceptable if you want the input to be on the same line as the prompt, your only guaranteed option is fflush:

printf("dimension du tableau? ");
fflush(stdout); /* printf uses stdout */
scanf("%d",&n);

Always, always, ALWAYS, ALWAYS DAMMIT, check input for failure. :)

/* scanf returns the number of successfully converted values */
if (scanf("%d", &n) != 1)
{
    /* scanf failed. recover or bail */
}
char *tab;
tab=(char*)malloc(n*sizeof(char));

Doesn't …

Banfa commented: Just for the 'ALWAYS DAMIT' I feel the frustration +1
Narue 5,707 Bad Cop Team Colleague

what is wrong here...

Side effects, my inquisitive friend:

int x = 2;
cout<< SQR(x++) <<'\n';
cout<< x <<'\n';

x is incremented twice due to the macro being nothing more than a textual substitution. Thus the expanded macro is x++ * x++ .

John Linux commented: perfect thank you +1
Narue 5,707 Bad Cop Team Colleague

Hi, I was wondering if the compiler Visual C++ is smart enough to optimize code like this:

string temp = "abcd";
string temp2 = "hahaha";
string temp3 = temp + temp2;

"temp + temp2" can be replaced by "abcdhahaha"

Actually, Visual C++ is smart enough not to optimize in that way. There are infinite possibilities in the side effects of calling member functions. Removing the call entirely could change the behavior of the program, so the optimization is prohibited.

vector<char> alphabet;
for (char i = 'a'; i <= 'z'; i++)
{
    alphabet.push_back(i);
}

can be optimized to:

vector<char> alphabet;
//Avoid dynamic allocation
alphabet.reserve('z'-'a');
for (char i = 'a'; i <= 'z'; i++)
{
    alphabet.push_back(i);
}

This optimization doesn't avoid dynamic allocation entirely, it lumps the progressive allocations into one (Visual C++ grows by half again the current capacity). Not a bad optimization, but it's very specific to the vector class and trivial for client code to implement as necessary. I very much doubt Visual C++ implements your suggestion.

Narue 5,707 Bad Cop Team Colleague

The answer is, absolutely nothing.

That's usually the answer to out of memory conditions. Most of the time all you can do is save state and terminate gracefully. The pointer is still usable, it just contains a potentially partial line. If recovery is possibly by freeing memory elsewhere, nothing stops you from calling io_gets again and pasting the two strings together manually (like you would when fgets reads long lines). I don't see this as an unreasonable situation unless out of memory conditions are common, and in that case you probably shouldn't be using something like io_gets in the first place. ;)

I couldn't agree more that some extra management functionality for the pool is warranted if it's to be truly usable in real code. For basic usage in the example, it's not a big deal. I appreciate you bringing it up though. Hopefully now I won't get bug reports that production code is failing because a pointer couldn't be removed from the pool. :D

Correct me if I am wrong, but the memory will be deallocated at the program exit time anyway.

You're not wrong, but you're not entirely right either. While it's common, this behavior is not guaranteed. Strictly portable code will release memory explicitly.

Narue 5,707 Bad Cop Team Colleague

Thanks for the comments. Good observations.

io_gets.c calls for #include <errno.h>.

Indeed. It's embarrassing to be anal about including all used headers explicitly and then get caught forgetting one in my own code.

BTW, why bother with errno at all?

I don't disagree. I did consider the various options for error handling, and ultimately decided to keep it simple. In this case, simple meant "write it without error handling, then splice in an errno solution".

I firmly (and humbly) believe that a library function may resort to errno only if it can't possibly flag an error in any other way.

I'm not sure I agree with that. There are few (if any) circumstances where errno is the only option. However, for rare errors other options can be too instrusive. For example, an output parameter for out of range conversions in strtol:

result = strtol(s, &end, 0, &out_of_range);

Is that extra parameter really necessary? Maybe, maybe not. But over the years I don't once recall anyone complaining about the design flaw of setting errno to ERANGE. ;)

I'd say, it forces the caller not to free it.

I suppose it depends on your perspective. If not having to call free feels like a straight jacket then we can word it in a bad way. If not having to call free feels liberating then we can word it in a good way. What's your take on garbage collection? ;)

I don't think it is right.

Right …

Narue 5,707 Bad Cop Team Colleague

I wonder why the following code work.

It doesn't. The recursive calls fail to fix the subtree:

if(root->data>item)
	root->left = insert(root->left,item);
else if(root->data<item)
	root->right = insert(root->right,item);
Narue 5,707 Bad Cop Team Colleague

In answer to a coworker's question today about memory management today, I wrote the following code. It's an implementation of the gets function that accepts an infinite length string (bounded only by the heap) and does not force the caller to free the resulting pointer.

I figure that it's a useful enough example of memory management and library design to offer as a Daniweb snippet.

I make no claims as to the completeness or correctness of the code, seeing as how it was written in the span of perhaps an hour. Though don't let that stop you from replying if you find any bugs or have comments.

jephthah commented: thanks for a great example of a meaningful way to use "Code Snippets" . +8
kvprajapati commented: Forever. +9
Narue 5,707 Bad Cop Team Colleague

If you got an offer to write a software, and your choices were only C and C++. Which would you choose ?

It depends on the needs of the software. From a very high level view I would most likely choose C++ to leverage the more comprehensive standard library.

I see so much advantages that C++ provides over C

Perhaps you could enumerate those advantages so that I can address them directly rather than dealing with vague terms. I often see people claim advantages in C++ that exist in C as well, or advantages that assume OOP is superior to procedural.

Only when you specify 'better' about what does it begin to be possible to make a useful answer.

Indeed.

The STL, by the way, is not particularly OOP unless you think that specializing templates is OOP (there are arguments each way).

The question was about container classes in particular. Unless you're the kind who thinks it's not OOP until you add inheritance, enough of the bases are covered to refrain from splitting hairs. ;)

Narue 5,707 Bad Cop Team Colleague

am seriously ready to pay a reasonable amount for this... around $20

Daniweb is not a programmer rental service. Offering to pay someone to do your homework is the kiss of death around here.

i need to submit tomorrow.

Congratulations, you've just gotten a lesson in time management from the school of hard knocks.

fp = fopen("C:\project\text1.txt","a+");

Double up the backslashes or reverse them, so they're not treated like escape sequences:

fp = fopen("C:\\project\\text1.txt","a+");
fp = fopen("C:/project/text1.txt","a+");

so '\t' is a tab character and '\p' is p (I think)

'\p' is an unrecognized escape sequence, and thus, undefined behavior.

tux4life commented: :) +8
Narue 5,707 Bad Cop Team Colleague

This reeks of homework, and nobody will do your homework for you. However, I'll offer some clarification where I feel the questions are incorrect.

explain with suitable examples the advantages these [container classes] give to the programmer over a procedural language such as C.

This question exhibits a common misconception that object-orientated languages are "better", which simply isn't true. "Different", yes. "Better", no. In fact, you'll find that well written procedural code follows most of the guidelines that make up the OO paradigm.

I see only two advantages that the standard C++ container classes have over C. This is certainly not the answer your teacher wants, but I think it's the most correct answer given the perspective of someone proficient with both languages:

  1. They're standardized. C doesn't have any standardized libraries for data structures beyond the native array type.
  2. They're type safe and relatively clean. C offers essentially two ways to create generic containers: pointers to void (which aren't type safe) and the preprocessor (type safe, but a maintenance nightmare). C++'s templates, while still complex, are a huge improvement.
Narue 5,707 Bad Cop Team Colleague

I think accessing the hard disk every time to get a file will be slower than getting all files from 1 access.

The system API is generally good at making these queries efficiently. Your other option is to read it all one time and then cache the results, which is fine for file structures that don't change and woefully insufficient the rest of the time.

Personally, I think trying to read the world into memory is a bad idea in the first place. You'd be better off only keeping a subset in memory at once for your visualization. The subset should be large enough to avoid excessive disk access all at once and small enough to load quickly when disk accesses is necessary.

But good luck finding your magic function that enumerates all files and folders on a volatile file system with a single disk access. When you find it, let me know, because I could use it too.

Narue 5,707 Bad Cop Team Colleague

>>Need a link back to the forum list

Unless I misunderstood, there already is a link back to the forum list near the top of the page.

If you're talking about the bread crumbs, it only goes back to the category, not the main list. For example on this thread:

Community Center > Daniweb Community Feedback > Short wish list

I want it to go one further (the way it used to be):

Forums > Community Center > Daniweb Community Feedback > Short wish list

Narue 5,707 Bad Cop Team Colleague

On the top level forum list

  • Not being able to collapse categories constantly irritates me.

In a forum

  • Need a link back to the forum list
  • Mark forum read and page links are at the bottom of the page. These should be available at the top of the page too.
  • Marking a forum read takes me to the category page. I think either not leaving the forum or going to the top level forum list makes more sense.
  • I think the Reaction column and Last Post column should be swapped.

In a thread

  • Need a link back to the forum list
  • Page links are at the bottom of the page. These should be available at the top of the page too.
  • The quick reply box needs an icode button.
  • The Similar Threads list seems randomly chosen. :icon_rolleyes:
Narue 5,707 Bad Cop Team Colleague

I am not very experienced in programming, but I think you can do this without using any of the functions like atoi(), etc....
Here's what comes to my mind:

1. Input the 'number' in the form of a string
2. for each character in the string, u can check if the ASCII value lies b/w 48(ASCII for character '0') & 57(ASCII for character '9') till you reach '\0' (if the condition is false at any point, u display the error message)
3. Otherwise, it means the user has input an integer. You can simply convert from a string to an integer by something like this:
multiply the character just before '\0' with 1 and store in an int (say int i=0), then the character 2 places before '\0' with 10 (then simply do i+=result), and so on....also note that before multiplying a character with 10,etc. subtract 48 from it....

I think this is simple enough....

Simple and broken. The listed algorithm fails to take signs into account and completely ignores the possibility of integer overflow. Doing this conversion manually is quite a bit harder than a lot of people realize. For example, here's a function that illustrates the work involved in only a partial implementation of the behavior supported by strtol. Notice how only a small portion of the code handles steps 2 and 3 of your algorithm. The rest is for error handling and robustness:

#include <cctype>
#include <cerrno>
#include <climits>

const char *parse_int(const …
Narue 5,707 Bad Cop Team Colleague

I am mildly surprised that using a stringstream is less efficient

It's makes perfect sense when you consider what's involved. Underneath iss>> value is a metric shitload of complex interwoven parts, only one of which performs a conversion from a streamed sequence of characters to an integer. On the other hand, strtol is very specialized and can be tuned for the sole purpose of converting a string to an integer.

I have also felt that the C++ stream library lacked the elegance displayed by say the STL containers.

The STL lacks a certain elegance as well, but yes, I agree with you. The stream library's biggest benefit to the programmer is type safety and extensibility (not a small benefit, to be sure). Beyond that it's too verbose for all but the simplest of cases.

jonsca commented: Can you translate a metric shitload to American units? :) +4
Narue 5,707 Bad Cop Team Colleague

Google for things like "keylogger source C++", or "global Windows hook C++". I don't personally have any code that I want to share, but the web is full of examples if you take the time to look around.

Kesarion commented: Thanks ! +1
Narue 5,707 Bad Cop Team Colleague

Just post your code, already. Ideally write up a bare bones program that exhibits your problem without being excessively long. Playing twenty questions is unproductive, especially when the problem sounds like something most of us can solve at a glance.

Narue 5,707 Bad Cop Team Colleague

Post your error code please.

I agree. The code is more or less fine. The using namespace std statement at the top of the date.h header could cause a problem, but that should have nothing to do with accessing public vs. private members.

You're trying to access a private variable from outside the class. void date::wordform(date d1) Although you're inside the date class, you're not inside the instance of d1.

All member functions of a class have access to private members, even members of different objects of the class. There's nothing technically wrong with date::wordform, though the design is confused (it should either be a member function with no parameters or a non-member function with one date parameter).

Ketsuekiame commented: Good answer and thanks for correcting me ^^ +1
Narue 5,707 Bad Cop Team Colleague

however neither of those are C++ they are part of the C standard library and C++ provides the same functionality through the use of stringstreams.

Just chiming in with a minor correction. atoi and strtol are most certainly C++. You shouldn't buy into the "pure C++" BS that encourages one to eschew all things inherited from C that have a C++ counterpart.

In this particular case, I've often found stringstreams to have a statistically significant overhead when compared to strtol (atoi is evil, of course, and should be ignored as a viable solution). Just because the functionality is the same doesn't mean the two options are equivalent. In performance critical code I've used strtol because it was just plain faster.

Narue 5,707 Bad Cop Team Colleague

Add a default constructor?

Narue 5,707 Bad Cop Team Colleague

pointers are the most difficult topic in c language so don't take it easily

Pointers are only the most difficult topic because people like you brainwash beginners into believing they're difficult. Pointers are in reality very simple.

Narue 5,707 Bad Cop Team Colleague

Sorry anuragcoder, I'm going to ignore you now. Hopefully you'll realize that flooding the forum with bad questions is counterproductive and start concentrating on quality rather than quantity.

In the meantime, here's some light reading for you.

Narue 5,707 Bad Cop Team Colleague

kbhit is a function. It returns a boolean value (in the form of an int) telling you whether there's a keypress waiting in the keyboard buffer. You use it like this:

if (kbhit())
{
    // A key was pressed
}
else
{
    // No key presses waiting
}
Narue 5,707 Bad Cop Team Colleague

Heck with the error.
I'm unable to find it.
Hint please...

How's this for a hint? Start over and work through your program slowly. Write test programs to teach yourself how things work, then use that knowledge to incorporate functions and constructs into your program.

In this thread I'm getting a distinct sense of helplessness and laziness. Probably the biggest reason you're not encouraging people to help is you're completely failing to help yourself first and you're not making the most of the help given.