deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Im sorry i just didnt know how to explain it well

You don't need to explain the mechanics, just the intended behavior. For example, what is the user of this feature trying to accomplish? What information do you need from the user and what result do you produce from that information?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i dont have YesNo buttons that was just an example

It would be prudent to explain exactly what you want. It's irritating when I give a viable answer to a question and then the response is "that won't work because what I asked for isn't really what I need".

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How about using a message box with the Yes/No buttons option?

switch (MessageBox.Show(prompt, caption, MessageBoxButtons.YesNo)) {
    case DialogResult.Yes:
        // Do something for yes
        break;
    case DialogResult.No:
        // Do something for no
        break;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

so I was wondering if me learning the win32 api is a waste of time and I should use some of the mentioned libraries for developing windows applications ???

No and yes, respectively. While you should prefer higher level GUI libraries for various reasons, it's still a good idea to learn the Win32 API because it gives you that much more flexibility. For example, I use .NET primarily, but when the framework doesn't do what I need or does what I need but too slowly, knowing the Win32 API means I can drop down a level and get the job done.

This happens more often than you'd think for production software because .NET is notorious for being sluggish on the redraw, and perceived performance is very important.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Mask just the low byte after shifting and you'll get what you want:

int red = (p >> 16) & 0xff;
int green = (p >> 8) & 0xff;
int blue = p & 0xff;

Coincidentally, I did this very thing today while writing an image skew detection algorithm.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm willing to be that count and totalwords are both int too, which means your division is performed in integer context. If the division results in a value less than zero, the precision is ignored and the result will be 0. You want something more like this:

int wordpercent = (int)((count / (double)totalwords) * 100)

This forces the division into floating point context, which retains precision so that it isn't lost before the multiplication step.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

By invitation only :)

Though there is at least one precedent where someone has asked to join the moderation team and that started the process.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Ahh but if I do that, what happens when I access the values in the body?

If the parameter names are the same as the data member names, the parameters will hide the data members when unqualified. This ambiguity doesn't exist in the initializer list, and it can be corrected in the body by qualifying with this:

this->x = x;
this->y = y;
Point(this->x, this->y); // But Point(x, y) works too since the values are the same
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

no deceptikon i have done this task in past and it worked for me actually the output will be like dis

Sorry, I'm having trouble deciphering the meaning of this sentence. Are you sure you're responding to something I said? If so, please quote it. Also, it would be nice if you used full sentence English rather than txt speak. Is it really so hard to type "this" instead of "dis"? Or "are" instead of "r"? Or "you" instead of "u"?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon Can u plz post the corrected code??

No. You wouldn't learn squat if I did the work for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Plz tell me where i am going wrong..

Start with the fact that you're double incrementing both ptr and i. Note how the increment clause of the for loop increments both of them, but in all other paths of execution in the body you still increment both of them.

Fix that and then trace through the execution in a debugger to see how your casing logic is actually working compared to how you think it works.

hello u can try like this where ascii value of a space is 32

Why are you using 32 when there's a character literal (ie. ' ') that doesn't depend on ASCII or ASCII-compatible character sets?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I find it odd that the implementation supports streams yet not completely. If the hardware couldn't handle stream behavior (presumably this is an embedded platform) then excluding that part of the library entirely would be expected. Rather, I don't recall any clauses in the ISO standard that say tellg() may be conditionally supported in the presence of an otherwise working iostream library, even for freestanding implementations.

But to the matter at hand, istringstream is really doing nothing more here than breaking the line down into fields and converting those fields. Since you already know that the >> operator is whitespace delimited, you can get the same value as stream.tellg() by counting delimiting whitespace for the first four fields:

getline(file,line);
{
    std::istringstream stream(line);
    UINT32 file_pos, fields;

    stream >> first >> second >> third >> forth;

    for (file_pos = 0, fields = 0; file_pos != line.size(); ++file_pos) {
        // Assuming fields are separated by only a single delimiter
        // and the line doesn't begin with whitespace. These are
        // fairly easy to handle, but I'll leave it to you.
        if (isspace(line[file_pos])) {
            if (++fields == 4)
                break;
        }
    }

    fifth = line.substr(++file_pos , line.length() - stream.tellg());
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this true or can I actually do this in C++?

One of the reasons why this is reasonable in Java is the lack of default arguments. In C++ you can do it all with one constructor:

Rectangle(int width = 0, int height = 0, int x = 0, int y = 0)
    : width(width), height(height), x(x), y(y)
{
    // Nothing necessary in the body
}

Note that I swapped x and y with width and height. For one thing I think it makes more sense conceptually, but also to support the second variant of Rectangle() from your Java code more easily.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem is that there are too many open files.

That's indicative of a design flaw. You can check the value of FOPEN_MAX (defined in stdio.h), and it's probably rather large for your implementation. If you exceed that value, you probably need to consider why you have so many files open at once and think about ways to avoid that.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Have you read the documentation for the XmlDocument class? It has methods for doing everything you want.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Also i would like to know the other methods of doing this.

My solution would probably be a double reversal. First reverse the entire string character by character (ie. "daS mA I"). Then go over the string again and only reverse each word. The end result is that the word order is reversed, but the characters in each word are normal (ie. "Sad Am I").

I'd also tighten up the definition of a word to just alphabetic and numeric characters. That way any punctuation can be ignored in the second step and retains the original position. But that's straying a bit from the problem definition and may need tweaking if it's not the desired result:

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

void reverse_string(char *begin, char *end)
{
    while (begin < end) {
        char temp = *begin;
        *begin++ = *--end;
        *end = temp;
    }
}

char *word_begin(char *s) { while (*s && !isalnum(*s)) { ++s; } return s; }
char *word_end(char *s) { while (*s && isalnum(*s)) { ++s; } return s; }

int main(void)
{
    char s[] = "The quick brown fox jumps over the lazy dog";
    char *begin = s, *end;

    reverse_string(s, s + strlen(s)); /* Reverse everything */

    /* Reverse individual words to restore them */
    while (*begin) {
        begin = word_begin(begin);
        end = word_end(begin);
        reverse_string(begin, end);
        begin = end;
    }

    puts(s);

    return 0;
}
nitin1 commented: good approach uses! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please review the following code and compare with yours. Take note of the comments and try to understand why I made the changes that I made. I tried to keep the spirit of the algorithm the same, even though I'd probably do this differently:

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

int main(void)
{
    char s[] = "I Am Sad";
    char str[10] = ""; /* Make sure to initialize str because its length is taken shortly */
    int i = 0;
    char *st2;
    char *st;

    st = &s[0];

    while (*st != '\0') {
        if (*st == ' ')
            st2 = st;

        *st++;
    }

    for (; strlen(str) < strlen(s);) {
        /* What if st2 == s? */
        if (*st2 == ' ')
            ++st2;

        st = st2;

        /* Don't reset i if you want to append to str */
        while (*st != '\0' && *st != ' ')
            str[i++] = *st++;

        str[i++] = ' ';

        /* Don't forget to skip whitespace or you'll always process the same word */
        while (st2 != s && *--st2 == ' ')
            ;

        /* Now find the previous word. Don't forget to check for the start of the string */
        while (st2 != s && *st2 != ' ')
            --st2;
    }

    str[i] = '\0';
    puts(str);

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The removing duplicates part has to be within that function.

That's a stupid requirement.

Even should be within that outer for loop.

I'm not entirely sure what you mean by that, but I'll assume that it means you can't split the tasks into two operations, and that both the sort and removal of duplicates must be interleaved.

If that's the case then I'd recommend using a temporary array to hold the result, then copying that result into the source array. The simplest method conceptually would be to find the smallest item starting at index 0 for every iteration of the outer loop (which would be infinite). If a smallest item isn't found, then you break from the loop. If it is found, count the occurrances from index 0 and copy those values into the next open slot of the temporary array. To make sure that duplicates aren't processed multiple times, you can set the counter for each instance of the smallest value to something like -1.

So in pseudocode:

# Sort and remove duplicates
while true
    min = 0
    found = a[min].count >= 0

    # Find the first unprocessed smallest item
    for i = 1 to N
        if a[i].count < 0
            continue

        if a[min].count < 0 or a[i].value < a[min].value
            found = true
            min = i
    loop

    if not found
        break

    count = 0

    # Count occurrences
    for i = 0 to N
        if a[i].value = a[min].value
            a[i].count = -1 # Mark as processed
            count …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The first part of that function is used to sort the words gathered in a text file from A to Z, the second part is meant to find any duplicate words

Pro tip: If the description of your function includes the word 'also', it should probably be refactored into multiple functions.

Your function does the work of two functions, and those two tasks are wildly different. Therefore there should be two functions: one to sort, and one to remove duplicates. Given a sorted collection, removing duplicates is trivial, so they can be run in sequence. If you do this then the task is greatly simplified from removing duplicates during the sort.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The buttons may only show posts which are currently negative or positive, so if someone voted down and someone else voted up, the net result would not be visible on either button.

Yup. The numbers show voting history on your account and the buttons retrieve currently positive or currently negative posts.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Honestly, I think having extra steps just to vote (ie. click to open the dialog, then click to vote) would turn people off to voting. The quickness of the present system encourages votes.

As for the confusion of which arrow the hover box is representing, perhaps adding an up or down arrow in that little box to make it more clear what you're doing?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hover over an arrow to add a comment and reputation. Click the arrow just to vote. The arrow you click on or hover over determines if it's positive or negative.

Aside from making a dummy dialog (which would ultimately be less user friendly as popups usually are) instead of splitting the two options with a hover over, I don't think we can simplify it any further. Though I'm open to suggestions. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What else could you need to know?

The contents of the file and enough context to test your code, obviously. For example, how have you defined WordStruct? Please compose a small test program that's complete, then post it here along with a sample of the file you're using. Reproduction of the problem is the first step in troubleshooting.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

any response will be highly apprciated.

When you down vote every response for frivolous and trivial reasons, I'm disinclined to do so. Goodbye.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but when you come to know that he dont have any worth of you and even laugh when you show respect to them, then that is a pathetic situaion. what about this ?

You take it up privately with him instead of airing your dirty laundry. And if what you suspect turns out to be true, simply walk away and move on.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'll give you a hint: check your array indices where the element is being set to 0. You're overrunning one of your arrays and count happens to be at that address.

nitishok commented: thanks. it works with a return; added in if(i==8) +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You keep resetting iResult in the inner loop when it shouldn't be modified. This is correct:

int iResult, iCount;

for(iResult=0; iResult<=iRows; iResult++) {
    for(iCount=0; iCount<=iResult; iCount++)
        printf("*");

    printf("\n");
}

Also notice that I added braces around the outer loop. While you can omit the braces if the entire body of the loop consists of only one statement, your outer loop contains two: the inner loop is one statement and the printf() call is a second. Failing to use braces here means that newlines won't be displayed at the correct time and you'll just have one long line of asterisks.

I recommend that beginners always use braces to avoid this kind of error.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It wouldn't work without an emulation layer or cross compiling with a Windows target. The format of object code files is different between Linux and Windows.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I wouldn't use bool for a bitset of error flags, but that approach isn't bad. In fact, iostream implementations will typically use it for the error state of a stream.

What kind of errors are these? Have you considered exceptions?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's pretty easy, if a tad obscure for those unfamiliar with locales in C++:

#include <iomanip>
#include <iostream>
#include <locale>

using namespace std;

int main()
{
    struct group_facet: public std::numpunct<char> {
    protected:
        string do_grouping() const { return "\003"; }
    };

    cout.imbue(locale(cout.getloc(), new group_facet));

    cout << fixed << setprecision(2) << 10000.00 << '\n';
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The file just isn't in the right place. Move it to your project folder along with the .cpp file and try again. If that doesn't work, move it into the debug folder with the .exe file for your program.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If I comment out one or the other I still do not get my .txt file to show.

The file you typed is never the file that gets read. Ever. Period. Why? Because you only use fin to read lines, and fin always uses "Show.txt". So is Show.txt the file that you actually have and want to read? If so, then it's not located in the correct place (as Walt said), and you need to do some error checking. Otherwise you need to stop opening Show.txt and use file to read lines instead.

perror() may work for you to get some additional error information:

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

using namespace std;

int main()
{
    string filename;

    cout << "Enter a file name: ";

    if (getline(cin, filename)) {
        ifstream in(filename.c_str());

        if (!in) {
            perror("Error opening file");
        }
        else {
            cout << "The file opened successfully\n";
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

ifstream file(fileName.c_str(), ios::in);
ifstream fin("Show.txt");

Which of those objects are you actually using? That's the problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If I were to implement this into the code I already have where would I put it?

It's a replacement for your code.

Will your code work for asking the user to input the .txt file of their choosing?

No, you'd need to add that part. Though it shouldn't be a big deal as you clearly already know how to do it (that part of your code is correct).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Any specific reason as I guess this is due to the version of DOS ?

The most likely reason is that I haven't worked with assembly in several years and while the logic was sound, the actual code is subtly (or blatantly) wrong somewhere.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I am getting this error when executing the code.

I guess you'll have to use the same logic and write working code then. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Does that include compiling the code or are you using a C++ interpreter? Because you don't just "run" C++ source code. Anyway, I can't tell you what's possible or not since you're closer to the problem than I am, but editing the code 100 times with a shell script seems silly from my perspective, especially when the only change is the sequence number after a couple of file names.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It seems like a better solution would be to edit the C++ code to accept input and output file names from the calling process, or run the whole thing in a loop a requested number of times from the calling process.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here's pseudocode for what you're doing:

cx = 10

while cx <> 0
    while cx <> 0
        int 21h
        dec cx
    loop

    dec cx
loop

So cx starts out as 10 and gets decremented to 0 by the inner loop. Then the outer loop decrements it again to make it negative and tests it against zero. cx is obviously not zero at this point, so the outer loop repeats. cx is still not zero, so the inner loop repeats.

Now you're looking at an underflow situation, where the inner loop will repeat until cx underflows, and hopefully wraps back around to 0. But ultimately this code represents a bug and should be fixed.

My guess would be that you're trying to use cx to represent two things (rows and columns) but the two nested loops are stepping on each other. You can get around that by saving and restoring cx around the inner loop:

; Print a right triangle

mov cx, 10     ; Decreasing number of rows remaining
mov ax, 1      ; Increasing number of asterisks per row

rows:
    mov dx, cx ; Save cx for later
    mov cx, ax ; Use ax's value for the inner loop counter

    cols:
        int 21h
    loop cols

    mov cx, dx ; Restore cx for the outer loop
    inc ax     ; Add an asterisk for the next row
loop rows

Another alternative would be to eschew the loop instruction and do it manually with two registers instead of one.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You create a new list on every iteration of the loop. Move the definition of ll outside of the loop and it'll work better.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yeah,but here supplying only integers(not unevaluated arithmetic expressions) will help.

Expecting someone, even yourself, to use a macro correctly is overly optimistic. The macro should be as dummy-proof as possible

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But when I enter "45:45" I get 45,4. The last character is missing.

Read all of my reply next time, I predicted this problem and explained and how to fix it. Bump up the size of your array by 1, and account for that new size in your call to getline(). Adding '\0' as the third argument to getline() is silly and pointless because you'll never recieve that character value in any reasonable situation. It also does nothing to deal with the actual problem which is insufficient storage in the string to hold all of the input.

And also, fflush(stdin); cin.get() is not working.

fflush(stdin) isn't guaranteed to work. fflush() is only defined for output streams. But that's not the problem, the problem stems from the fact that you're trying to overfill your input string. getline() is smart enough to recognize that this is bad and puts cin into an error state, which you can see by adding one line before fflush():

cout << boolalpha << cin.fail() << '\n';
fflush(stdin);
cin.get();

You'll notice that it prints "true" because cin is in a failure state. Any requests for input either through fflush() (probably, I'm making an assumption about how your compiler's standard library works) and certainly get() will do nothing. The effect is like get() is implemented as so:

int istream::get()
{
    if (!good())
        return;

    // Do actual work...
}

If you fix the underlying failure, you'll fix the get() too. And if …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

strtok() is funky in that it works using an internal state through multiple calls. To get the next token you need to call strtok() again with a null first argument (so that it knows to use the previously passed string):

output=strtok(input,":");
while(output != NULL)
{
    cout<<output<<endl;
    output=strtok(NULL,":");
}

Oh, and your input string and getline() call need to account for that pesky little '\0' at the end. Otherwise your last token ("CD") will be trimmed by a character because it's still stuck in the input stream.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Awesome! So i can display any error statement like this??

It depends on what you mean by "this". Note that what I showed you is the internal setup of perror() on my standard library implementation. You can't simply toss my __errno_map into your code and expect perror() to change how it works on the compiler you're using.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this the list you're talking about??

For Microsoft's perror(), yes. Other implementations of the standard library may have different values of errno that are supported and different messages. For example, my implementation presently maps errno values like this:

extern struct _errno_mapping __errno_map[] = {
    {EDOM,     "EDOM",     "Domain error"},
    {EILSEQ,   "EILSEQ",   "Encoding error"},
    {ERANGE,   "ERANGE",   "Range error"},
    {EINVAL,   "EINVAL",   "Invalid argument"},
    {ENOENT,   "ENOENT",   "No such file or directory"},
    {ENOMEM,   "ENOMEM",   "Not enough memory"},
    {EIO,      "EIO",      "I/O error"},
    {ENFILE,   "ENFILE",   "Too many open files"},
    {EACCESS,  "EACCESS",  "Permission denied"},
    {EUNKNOWN, "EUNKNOWN", "Unknown error"},
    {ESETP,    "ESETP",    "Error setting file position"},
    {EGETP,    "EGETP",    "Error getting file position"},
    {ESFMT,    "ESFMT",    "Unexpected string format"},
    {-1,       "",         ""} /* Sentinel record with an invalid errno value */
};

Where the sentinel implicitly gets converted to "Unrecognized error" in strerror()'s implementation:

/*
    @description: 
        Maps the number in errnum to a message string.
*/
char *strerror(int errnum)
{
    size_t i;

    /* Simple case for no error */
    if (errnum == 0)
        return "No error";

    /* Look for a matching errno code */
    for (i = 0; __errno_map[i].code >= 0; ++i) {
        if (__errno_map[i].code == errnum)
            return (char*)__errno_map[i].msg;
    }

    return "Unrecognized error"; /* Give up ;) */
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How about a lazy update of the cells? It really doesn't matter what the contents of a cell are until you access it for the latest value. Unless the value of a cell depends on all previous cells, you can apply the update as needed rather than en masse, and that would save a huge amount of time.

The only caveat would be an extra bit of storage necessary to flag whether the cell has its latest value or needs to be updated.

If the values do cascade somehow, you'd probably still get some performance benefits, though it would be more amortized than absolute. In that case something like r0shi's idea would work, where you apply the change to all cells dependent on the current cell retroactively or recursively depending on how difficult the cascade is to reverse.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The output shows "No error"

Probably because there's no error. perror() writes the value of errno in human readable form, along with an optional user provided message. It can literally be implemented like this:

/*
    @description:
        Maps the error number in errno to an error message.
*/
void perror(const char *s)
{
    if (s && *s) {
        fputs(s, stdout);
        fputs(": ", stdout);
    }

    puts(strerror(errno));
}

There are only a handful of places in the standard library that are required to set errno to something specific (mostly math functions and multibyte en/decoding); everywhere else is optional and implementation defined. Neither printf() nor scanf() are included in those handful of places.

You're not using perror() incorrectly, as Walt mentioned, but for an application defined error such as exceeding MAX_VAL, you're on your own for setting errno:

if (x > MAX_VAL) {
    errno = ERANGE;
    perror(NULL);
}

So, which function shall i use?? for c++ we can use cin.get(); but what to use for C??

The equivalent of cin.get() in C is getchar().

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If at all there is a differnce between their execution times in the range of nanoseconds or picoseconds?

Execution is measured in "waste of programmer time" intervals that increase in direct proportion to the triviality of the statement.

Ancient Dragon commented: LOL +14
iamthwee commented: ha ha ha... ha +14
WaltP commented: Love it!! +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your code runs fine on my end (with minimal tweaks to make it compile as C90). What compiler are you using, what output are you getting (paste it), and what output do you expect (paste it too)?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here's a hint for asking questions: if reproduction of your problem depends on the content of a file, it's a good idea to post a small part of that content along with your code. This way we aren't forced to imagine what your file looks like and devise test cases in the hope that we'll hit your problem. Most helpers will just pass this question by because it implies too much work for what promises to be a very simple issue.