deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The date() function takes two arguments. The first argument specifies the date format you want the timestamp to be converted to. The second argument specifies the timestamp that will be converted. Without the second argument, how does the date() function know what the date is?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please post a small sample of your database file.

edit: And fix the following:

if(ch==alphabet)            /* if found then increment the number of bytes and check the size
{                              of a given entry */

The opening brace is caught up in your comment. I assume you fixed it in the real code, because otherwise it wouldn't compile at all, much less create an infinite loop at runtime.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I considered forcing you to post the actual error message rather than the error code because most people haven't memorized all of the codes for Visual C++. But if you prototype your min() function, you'll fix those two and be left with the rogue semicolon in one of your output statements.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For starters, if you're ever going to expect to compare ch against EOF, then you must declare ch as int. You'll notice that all of the character I/O functions work with int, and the reason for that is EOF.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

lets use calloc() instead of malloc()

Okay, but that's not going to improve matters. If anything it'll make the code slower because on top of allocating memory (that's another extremely expensive operation), calloc() has to initialize it.

But the thing is program takes .685 seconds to complete and I want to reduce the time to .3 seconds.

I assume you're measuring using a profiler? Why have you picked .3 seconds as the end all be all of performance on this seemingly pointless program? What makes you think .6 seconds isn't fast enough? All of this seems very arbitrary to me, so I'm wondering what you're actually trying to accomplish.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

because bl is capable of handling more and much intense instructions, am I right?

Not really. AL and BL are functionally identical, but because AL will be reused almost immediately by the next few instructions, its contents must be saved into another register or they'll be lost.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What I don't understand is, would a real world program have a default constructor AND a constructor with parameters?

Certainly, if there's a case where the class could initialize itself to a predictable state without help from the caller. One example might be an empty string, so std::string has a default constructor that initializes itself to the equivalent of "".

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I was reading somewhere in a forum that using switch case to do file handling was unstable.

That's nonsensical. Nothing about a switch or "file handling" in general discourages stability. It's certainly possible to write brittle code, but that's a problem with the programmer, not the constructs being used.

So I'd say that whoever wrote what you were reading either meant something else, or was quite confused.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The most common password is "123456"

I used "12345" for the longest time on my Hotmail account. Then they changed the requirement to 8 characters and it became "12345678". :D

p.s. I use a much stronger password now, so don't bother trying either of those.

I use almost the same password for everything, very strong with upper case, lower case, numbers and special characters.

That's what most people do. Either that or cycle between a handful of passwords.

tux4life commented: 12345678910 <- strong password ;) +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Do i just have to put a * instead of + and prodcut instead of sum? If so it didn't run.

Nope, you also need to define and initialize v1 and v2. Then it'll work:

#include <iostream>

int main()
{
    int v1 = 2;
    int v2 = 5;
    std::cout << "The sum of " << v1 << " and " <<v2 << " is " << v1 * v2 << std::endl;
    return 0;
}
Kareem Klas commented: Thank you! It helped me alot. Weird that the book didn't say me to define and intialize v1 & v2. Really thanks alot! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Btw, you, again, introduced three map lookups where only one is needed

Because, again, I'm not especially concerned over what I feel is a negligible cost.

The best, simplest and clearest solution would certainly have been to store them by value, but short of that, go with unique_ptr.

I don't disagree, but you're neglecting the arbitrary restrictions I put in place when writing this code. Unless you have an example of using unique_ptr without any explicit use of new or raw pointers, I'll stand by my choice of shared_ptr. Off the top of my head, I can't think of any way to use unique_ptr directly without violating one or both of those restrictions.

Dumping those restrictions and with more of an eye toward map performance, I'd probably go with something more like this (quickly done, so please excuse any bugs or obvious omissions):

#include <iterator>
#include <map>
#include <memory>
#include <stack>
#include <string>

template <typename CharT>
class trie {
    struct node {
        std::map<CharT, std::unique_ptr<node>> link;
        bool terminal;
        CharT key;
    public:
        node(CharT key): terminal(false), key(key) { }
    };

    std::unique_ptr<node> root;
public:
    trie(): root(new node(CharT())) {}

    /*
        @description:
            Adds a word path specified by s to the trie.
    */
    void add(const std::basic_string<CharT>& s);

    /*
        @description:
            Removes a word path specified by s from the trie.
    */
    void remove(const std::basic_string<CharT>& s);

    /*
        @description:
            Searches for the prefix s when require_terminal is false or exactly matches
            a terminal path created by add() when require_terminal is true.
        @returns:
            basic_string::npos is …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

are there any other suble changes from C++ to C?

Yes. Click Here.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In text mode, look for '\n'. In binary mode, look for '\r' followed immediately by '\n'.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In text mode the newline sequence will be converted to '\n', this is true for any platform. In binary mode you're on your own, no translation will occur so on Windows you need to look for and handle newlines in the form of CRLF.

But it's problematic because you can get a text file formatted using POSIX newlines (just LF rather than CRLF). So if you just look for CRLF or rely on text mode translation the lines might not be split correctly. Fun, huh? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just to make things crystal clear, NULL is a macro intended for use as a null pointer, it should never be used as the null character ('\0', also known as NUL with one L). While in C++ NULL is defined as 0 and that's compatible with the null character, it will confuse the bejeebus out of readers of your code.

So to summarize best practice:

  • In pointer context use nullptr. Prior to C++11 use either NULL or 0.
  • In character context use '\0'. 0 is acceptable, but not recommended.
  • In integer context use 0.
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I notice that add() got broken in your changes. It just traverses the (probably nonexistent) path rather than adding keys where they don't exist. You'd end up dereferencing null pointers unless new nodes are added at the right places:

template <typename String>
void add(const String& s) {
    auto it = &root;
    // Traverse the path and extend it as necessary
    for (auto c : s) {
        if (!(*it)->link[c]) {
            (*it)->link[c].reset(new node());
        }
        it = &( (*it)->link[c] );
    }
    (*it)->terminal = true;
}

Is there any reason at all for using a shared_ptr<node> for your links?

Yes. It's not a good reason, but I do have a reason. ;)

Why not use a unique_ptr<node>?

Ultimately it comes down to two things:

  1. As an arbitrary restriction I didn't want to use new explicitly, and there's no std::make_unique(). I could have written my own make_unique(), but like I said, it's just a reason, not a good one.

  2. I didn't want to diddle about working around unique_ptr's ownership rules with non-owning aliases, and as another arbitrary restriction I didn't want to use raw pointers at all.

For this class, I'm not especially concerned about the overhead of shared_ptr, so I went with what at the time felt like an easier approach. If it were intended as a serious library I'd put more work into optimization.

const-correctness for the match() function (doesn't change the object);

Bugger, I totally forgot to make match() const. Thanks for the …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please tell me how to optimise.

Delete the printf() line. I/O constitutes some of the most, if not the most time intensive operations.

On a side note, your code exhibits undefined behavior by accessing uninitialized memory. There's no guarantee that the program won't crash intermittently.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

King book where no strings are covered and I have to do this only by arrays and loops not by string functions like you.

Can you not read? I already stated that the only string function I used was strrev(). I also essentially duplicated the effect of strrev() later in the code without using any other string functions. You can replace size_t with int, the strrev() call with a facsimile and there will be nothing from the string.h header used in that code. It's mostly a manual solution, though to be honest that's only because strrev() isn't suitable for reversing substrings.

I can't tell if you're really as stupid as you're presenting yourself, or just pissed off that I'm forcing you to use your brain and do actual work.

I think you can't solve this question by another method without strings.

If you mean without string functions provided by the standard library then I'll direct you to exhibit A, where I've written all of those functions. I'm in no way dependent on the standard library. If it's not there, I'll just write it myself (and I have). Can you do the same?

So you might consider that just because someone refuses to do your homework for you, it doesn't mean they're unable to do it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

arrays are the same thing as pointers(arrays are a series of pointers)

Wrong on both counts. Arrays are not pointers, period. There are two situations where C can trick you though:

  1. In value context (which happens to be most of the time), an array name will be converted to a pointer to the first element. The very fact that sizeof when used on an array will give you the total bytes taken by the array rather than the bytes in a pointer is enough to prove that arrays are not pointers. The operand to sizeof is used in object context, not value context, and it's one of the places where the conversion doesn't happen.

  2. In a function signature (barring C99's VLAs and advanced array notation), the first dimension of an array parameter is internally converted to a pointer and the size is ignored. So these three signatures are functionally identical:

    void foo(int a[10]);
    void foo(int a[]);
    void foo(int *a);

Let's look at some problems with your code:

long int fib[user];

C doesn't support using const variables as the size of an array because const doesn't mean constant, it means read-only. That's a subtle but significant difference. It's possible you're using C99's variable length array or a compiler extension, but it's equally likely that you're accidentally compiling as C++.

scanf("%d", &user); //asks how many numbers to do

user is a const variable. This scanf() call is just asking for trouble.

Really all …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

scanf("%"PRIu16, &y);

The PRI* macros are for printf. Use the SCN* macros for scanf, they're not interchangeable:

scanf("%"SCNu16, &y);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I just asked that is there is any shorter version of this using only loops and without string.h and ctype.h header.

No. And you should probably stop thinking of 40 lines as "long", because that's teeny tiny from my perspective.

And by the way I'm a self learner not a university student.

That's completely irrelevant.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hey, I already mention that the question must be done without string.h header function.

And I'm not going to do your homework for you.

I can also do this by your way, but I want to do this without string.h header function.

The only thing I used from string.h is the non-portable strrev() function, which is super easy to write. You can even learn how to write it by looking at the code I gave you. What I'm getting from your response is that you didn't bother to read the whole of my post and refuse to take similar code and learn from it to write code better suited to your specific problem.

In other words, why should I bother helping further when you don't seem interested in helping yourself?

Also this is not a homework.

It's an assignment of some sort that you've been given or taken upon yourself to complete. Therefore, it's homework under Daniweb's definition of the word.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

On a side note, I figured that trie code was useful enough to post as a code snippet. So I updated it a bit and created one.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't cage a swallow can you?

I'm assuming you meant the reversal to be "you can't swallow a cage can you?", because the one you posted would require a bit more work in specifying which words are being reversed as opposed to reversing all of them.

And the "hint" actually tells you the whole algorithm:

#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    char s[] = "you can cage a swallow can't you";
    size_t begin = 0, end;
    size_t i;

    puts(s);

    /* Reverse the whole string */
    _strrev(s);

    /* Reverse each word in the string */
    while (s[begin]) {
        end = begin;

        /* Find the end of the word */
        while (s[end] && !isspace(s[end])) {
            ++end;
        }

        /* Reverse the word */
        for (i = end - 1; begin < i; begin++, i--) {
            char temp = s[i];
            s[i] = s[begin];
            s[begin] = temp;
        }

        /* Find the beginning of the next word */
        begin = end;

        while (s[begin] && isspace(s[begin])) {
            ++begin;
        }
    }

    puts(s);

    return 0;
}

And before you cry that I didn't comply with the restrictions of the assignment, it's not my assignment to do, so you can use my code as a template but not turn it in for a grade.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't know about you, but the error I got was complaining that your node structure is incorrect. The next node should be a pointer to node, not a pointer to int:

struct node{
    int id;
    node *next;
};

I didn't look any further since that right there was a deal breaker for the program. Apply the fix and see if it helps.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As the title says, it's a simple trie class written in C++11. The only operations implemented are insert, remove, and search (both prefix and exact matches). I sort of abandoned the test/debug process, and while I'm somewhat confident that there aren't any serious bugs, I can't guarantee it. Use this class at your own risk. ;)

nitin1 commented: well done sir!! :-) +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can use a dynamic array instead of an array. This is a classic trade off of speed versus space, because the dynamic array will be drastically slower while the static array will take up more overall space for your average case (assuming the average case is a half full array of links).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please that would rather make it too complex.

Trying to copy something that's not designed to be copied isn't any better.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

then after allocating memory to it, why not it is made part of the complete tree

Because it's too late at that point. Once temp points to NULL, it's no longer related to the tree.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Change your code so that you don't fight the design of Qt. QObjects are non-copyable by design, and that was an explicit choice, so making it happen will be inherently awkward and brittle.

How about instead of keeping a copy, which I assume is because you want to have a transaction that can be rolled back, store a stack of edits and roll them back individually like an undo queue.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Consider this implementation of the standard library. size_t is defined as:

/* size_t is defined in multiple headers */
#ifndef _HAS_SIZET
#define _HAS_SIZET
typedef unsigned size_t;
#endif

That's all it is! Don't read too much into it, size_t is nothing more than a typedef for one of the supported unsigned integer types. It's used for a huge number of things such as collection sizes, counters, indexes, etc... Pretty much all of the places an unsigned integer would work, size_t can be used when you don't so much care about the exact type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How i can combine them together ?

That depends on your compiler, really. If you're using an IDE you can just lump everything together in the same project and then build it. The IDE will take care of the grunt work. If you're using a command line compiler, they tend to be fairly consistent in that you provide all of the .c files for compilation (the .h files will be handled automatically) and they will be compiled then linked into an executable:

$ gcc SetADT.c main.c

You can also compile them separately and link them:

$ gcc -c SetADT.c
$ gcc -c main.c
$ gcc SetADT.o main.o

The options and extensions may be different, but that's the general pattern for command line compilation.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How about this one?

Not bad for a basic attempt at iterative and recursive algorithms. Given that the complexity of the recursive fibonacci algorithm is horrendous, I'd also include a memoized version:

int Fibonacci_Recursion(int n)
{
    if (n < 1) {
        return 0;
    }
    else if (n < 3) {
        return 1;
    }
    else {
        int value = find(n);

        if (value != -1) {
            return value;
        }

        value = Fibonacci_Recursion(n - 1) + Fibonacci_Recursion(n - 2);
        save(n, value);

        return value;
    }
}

I especially enjoyed this comment: "I think implementation in recursion is better because it call itself recursively". It's a completely nonsensical and irrational reason for calling the recursive implementation "better", especially given that between the two I'd choose the iterative version 10 times out of 10 because it uses O(n) time and O(1) space. Even the memoized recursive version uses O(n) time and O(n) space, and it's more complex.

On a side note, you're allowed to use the space bar. Coding in C isn't a contest to see who can write the most compact tokens, and judicious whitespace will make your code much easier to read.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you're writing code that depends on an exact data type size (and often on a data type size in general), you're probably doing something wrong.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem is on line 47, where you overwrite temp but temp was already NULL, so the tree doesn't reflect the change. I'm also concerned that you may be somewhat confused as to how a trie works. Consider the following example:

#include <limits>
#include <memory>
#include <string>
#include <vector>

template <typename CharT>
class trie {
    struct node {
        std::vector<std::shared_ptr<node>> link;
        CharT key;
    public:
        node(CharT key): 
            link(std::numeric_limits<CharT>::max() + 1), 
            key(key)
        { }
    };

    std::shared_ptr<node> root;
public:
    trie(): root(nullptr) {}

    /*
        @description:
            Adds a word path to the trie.
    */
    void add(const std::basic_string<CharT>& s)
    {
        if (root.get() == nullptr) {
            root.reset(new node(CharT()));
        }

        auto it = root;

        for (auto c : s) {
            if (it->link[c] == nullptr) {
                it->link[c].reset(new node(c));
            }

            it = it->link[c];
        }
    }

    /*
        @description:
            Returns the first index in the string s that doesn't match 
            a path in the trie, or npos for a complete match.
    */
    typename std::basic_string<CharT>::size_type match(const std::basic_string<CharT>& s)
    {
        auto end = s.begin();
        auto it = root;

        while (end != s.end() && it->link[*end] != nullptr) {
            it = it->link[*end++];
        }

        if (end == s.end()) {
            return std::basic_string<CharT>::npos;
        }

        return end - s.begin();
    }
};

Note in the add() member function how I carefully checked for a null root and then make sure to only access child nodes for assignment. This is one method for ensuring that changes to the data structure are propagated back to the top.

nitin1 commented: awesome code!! i added it in my diary :) +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

tl;dr - Everyone starts as a newbie but you only learn by exploring and using the things you don't know about.

I want to preface this with the comment that there's no malice or judgement in this post, it's just an observation based on limited experience.

I'm reminded of the difference between "newbie" and "noob" in MMO circles. A newbie is a beginner, any ignorance is temporary as they learn how things work. A noob is willfully ignorant and refuses to learn regardless of how long they've been playing.

riahc3 strikes me as the type that reached a point of being able to write code that "works" and doesn't want to continue improving. What he knows is sufficient to do what he wants, and that's all that matters. Granted this is an observation over the course of maybe three threads, so it's hardly a statistically significant sample.

ddanbe commented: Very well spoken, like your signare. +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Look at the picture.

Unfortunately, hidden whitespace isn't easily seen in a picture.

Suggestion, instead of making the code validator look for tabs, 4 or more spaces or curly braces, why not if there are tabs, 4 or more spaces or curly braces........IT TURNS THAT TEXT INTO CODE FORMATTING?!?!?!

Because having non-code in a code block isn't a great deal better than having code outside of a code block. Since it's difficult to guess what the author of a post intended to be formatted as code, that decision is deferred to them with a validation error in cases where they may have forgotten to apply a code block.

My personal preference would be to update the validation code such that it isn't quite as aggressive in terms of whitespace (eg. trailing or embedded whitespace is ignored). I tried that at one point and Dani reversed it, but for the life of me I can't remember what the reason was.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just use the addition operator:

select column1 + column2 from mytable;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

OK Ive been able to post it but without the text that I put after. What is wrong with it?

Cross posting your question makes it more likely that you'll miss the answer. Please see your other thread on the subject for my response.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

OK, its the text I put after the snippet. What is wrong with it?

The code validation check looks for tabs, 4 or more spaces, or curly braces anywhere in the post. If those things are outside of a code block, you'll get the error message.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's a date like "2012-11-28" still the error appears

Since you've marked this as solved, I assume you found that the second argument is supposed to be a timestamp as per the PHP manual, yes?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Echo the value of $dtime and see what its value is.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why does the coordinator need a completely separate table and functions? Typically administrative users are still users, the only difference is permissions attached to the account.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Then checking for garbage values is as simple as this:

int value;

if (!(cin >> value)) {
    /*
        The stream begins with garbage
    */

    // Restore the stream to a good state
    cin.clear();

    // Clear the entire line since you don't know where the garbage ends
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

Formatted input will validate the contents of the stream for you, and probably far more completely than if you tried to validate integers manually.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The word "garbage" is meaningless outside the context of your problem domain. You need to define what it means to your program. For example, if the domain of the program is to read numbers from 0 to 10, then anything that's not a number and any number outside the range of 0-10 constitutes garbage.

So...what input does your program expect, and what input falls outside of that expectation? You want to identify and allow only the expected input and treat everything else as garbage.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Then you need to figure out what the heck a "garbage" value is before you can tell the computer how to recognize one. You can't write code to do something you yourself are unable to do manually.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you define students as an integer that matches the size of the array, sure. But within the given code, it'll fail with a syntax error because students is undefined.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How do you know if a value is a "garbage" value?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just taking a technical look at his comment for a moment...

I can only assume that you think everyone but you has misread the post and failed to take into account that particular interpretation. Thanks for the vote of confidence. ;)