deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is char** val the same as char* val[ ]

Only as formal parameters in a function definition. Otherwise, they're not. I'm assuming we're talking about parameters for the answer to your next question.

when is the formal (char** val) used

I'll use the array notation when I'm absolutely sure that the function is intended to work with an array or simulated array. I prefer to use pointer notation when the object is known to not be an array or whether it's an array is unknown.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I received an exception when I tried to pass the above string.

What exception did you get and which version of the .NET framework are you compiling against? This works for me on .NET 3.5:

using System;
using System.Xml;

public class Program
{
    public static void Main()
    {
        try
        {
            var doc = new XmlDocument();

            doc.LoadXml("\n <div> attrib1=\"test\"</div>");

            Console.WriteLine(doc.OuterXml);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's somewhat amusing how you managed to pick the two worst possible options. gets() is completely unsafe, and the latest C standard actually removed it from the library. scanf()'s "%s" specifier without a field width is no better than gets(). In both cases input longer than the memory can hold will cause buffer overflow. They also do different things in that gets() reads a whole line while scanf("%s"...) only reads up to the nearest whitespace.

The recommended go to solution is fgets():

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

int main(void)
{
    char buf[BUFSIZ];

    printf("Enter a string: ");
    fflush(stdout);

    if (fgets(buf, sizeof buf, stdin)) {
        buf[strcspn(buf, "\n")] = '\0'; // Optionally remove any newline character
        printf("'%s'\n", buf);
    }

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

only small thingy left here is that in the 2nd method, the one you suggested, the loop is doing one extra iteration at the end.

That's the base case where size is 0. The only reason it's "bad" in this case is because of the debug printf() accessing the array out of bounds, but the algorithm is otherwise correct. If you "fix" the problem then you'll end up with an algorithm that fails to find the smallest value when it's the last one in the array.

The correct fix would be to avoid dereferencing the array until after it's confirmed that recursion hasn't reached the base case:

int findMin(int *arr, int min, int size)
{
    if (size == 0) {
        printf("in findMin() : passed values >> min:%d  size:%d\n", min, size);
        return min;
    }

    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n", *(arr), min, size);

    if (min > *arr)
        min = *arr;

    return findMin(arr + 1, min, size - 1);
}

But these debug printf() calls should be either removed or conditionally excluded anyway, because you don't want to see them once you're confident that the function works as intended.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Get Turbo C, install it, create a project, and write the code for it. Do you seriously think your question is meaningful?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Does it make a functional difference or is it just a formatting preference?

It's a formatting preference, assuming I understand your question. C# inherits a C rule wherein if you don't include braces on a compound statement (eg. if, while, or using), the next statement constitutes the body. So you can chain usings like you did:

using (TcpClient clientSocket = new TcpClient(host, port))
    using (NetworkStream clientStream = clientSocket.GetStream())
        using (StreamWriter toOmega = new StreamWriter(clientStream))
            using (StreamReader fromOmega = new StreamReader(clientStream))
            {
                ...
            }

And the functionality is as if you did this:

using (TcpClient clientSocket = new TcpClient(host, port))
{
    using (NetworkStream clientStream = clientSocket.GetStream())
    {
        using (StreamWriter toOmega = new StreamWriter(clientStream))
        {
            using (StreamReader fromOmega = new StreamReader(clientStream))
            {
                ...
            }
        }
    }
}

Because the braces aren't needed for all but the innermost statement (unless its body only consists of a single statement), you'll often see an unindented chain because it tends to look cleaner than the unbraced indented version:

using (TcpClient clientSocket = new TcpClient(host, port))
using (NetworkStream clientStream = clientSocket.GetStream())
using (StreamWriter toOmega = new StreamWriter(clientStream))
using (StreamReader fromOmega = new StreamReader(clientStream))
{
    ...
}

But some people (myself included) feel that this obscures the structure of the code, and prefer the fully braced and indented version.

do the repsonses pile up in a buffer that can be read sequentially like this?

Yes. You might consider using WriteLine() instead of Write() though, so that ReadLine() finds …

Ketsuekiame commented: Unfortunately straight line compound is becoming more popular in the junior devs we get here :( +8
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You only allocated memory for p4. p3, p2, and p1 are all still uninitialized.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if usrnme is wrong and pass is correct, it will say "intruder alert"

If the user name is wrong, how do you know the password is correct? Systems that allow only one user are dumb. Telling intruders that they're using the correct password and only need to figure out the user name is even more dumb. ;)

if both are wrong, it will say "you are not welcome here"

I fat finger my login credentials all the time; it would be disheartening if my software told me I wasn't welcome because I had difficulty typing.

tux4life commented: You're always right, and if you're wrong I wouldn't notice ;) +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Think about it, a question being solved 8 years ago (the original poster has not returned for 8 years) is suddenly spammed today by a newbie poster and brings it back even though it is already solved... isn't that a problem?

Spam is a different thing than a newbie posting in a thread that's solved. And even if the original question is resolved, there's no reason why the discussion couldn't be continued if someone else has relevant questions or comments.

Unless Dani, you (deceptikon), and whomever does the programming sets up a way for users to permenantly close their own threads so they don't have to take in anymore solutions

The OP isn't the only one who benefits from a thread.

or have a "timer" that closes threads permantly after a few months of being "dead".

This is what I meant by automatically locking threads.

Wouldn't those be helpful features to prevent spam?

True spam should be reported so that it can be removed by a moderator. Legitimate posts are allowed, and if they're not relevant to the thread should also be reported.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

By any chance is Dani developing a way to permenantly close "dead" threads, to prevent spam?

No, and there are no plans in the future for such a feature. Dani encourages relevant thread resurrection, and I would fight tooth and nail to stop automatic locking because I've seen it done in practice and the result is exceptionally unpleasant. At the very least there would need to be another solution.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Anybody got any views on this? Is common civility something to be shunned in order to avoid offence?

I was raised to be polite and courteous to all, women and men regardless of age. If someone is offended by that, it's not my problem. If a woman gets offended by me holding a door for her (which I would do for anyone a few steps behind me), my thought is "Fuck you, bitch, I'm just being nice. Don't read too much into it". I wouldn't actually say that because it would be rude, but seriously, can't we all just be less sensitive and accept kindness for what it is?

There's a line, of course. I wouldn't offer my coat to someone except in truly extreme circumstances, and I'd only offer my seat to someone who clearly needs it more than me. But smiling, holding doors, offering a place in a grocery line to someone who has greatly fewer items, these are what I see as common courtesy. It's not about feeling superior, it's about not feeling and looking like a selfish douchebag.

Chivalry is associated with a time in history when women were considered property.

There's some truth to that, though as I understand it chivalry itself was more about honorable knightly behavior. This included respecting the honor of women but wasn't specifically targeted toward women. Perhaps you're confusing chivalry with male chauvinism?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I want to know that since the sizeof is compile time operator then why does thee above code outputs 4 even though the call to foo() will be made at runtime.

You'll notice that foo() isn't called when used as an operand to sizeof:

#include <stdio.h>

int foo()
{
    puts("foo!");
    return 5;
}

int main(void)
{
    printf("%d\n", sizeof(foo()));
    return 0;
}

That's because sizeof only evaluates the result of an expression, even if the expression contains runtime-only components or would be completely invalid if actually run. Another example is with malloc():

int *p = malloc(sizeof *p);

Dereferencing an uninitialized pointer is a horrible idea, but because sizeof evaluates the result as if the expression were run instead of actually running it, the above line is completely safe and even recommended.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Download a reference manual and use it is my advice.

That's too much work when they can just post their problem to umpteen forums with the expectation that some kind soul will do it for them.

I'm not an IT professional, I'm a hobbyist, and I've learned all I know by research, and testing and more of the same!

Even among professionals, you're a rare breed. More and more I find that I can no longer assume that the developers and IT specialists I work with have any clue how to do their job.

tux4life commented: That secures your job position :D +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Technically all you need is the compiler and a text editor. In fact, it's usually recommended that you get comfortable doing everything from the command line before moving to an IDE because the IDE, while more productive, tends to hide things from you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

as long as the new posts are relevant to the topic.

The susggestion takes that into account. We still have issues with people resurrecting threads with new or unrelated questions, or with posts that have no value (eg. "Thanks for sharing!" posts). I wouldn't be surprised if a more naggy approach to notifying people that the thread is old helped to alleviate at least some of the problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The enter key is a character too, yet you don't account for it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

deceptikon, your method compiled just fine but didn't actually change the output of the number. If I entered 12345 it would still out put 12345 rather than 012345 which is what I'M trying to get.

Let's make something abundantly clear: the type of string matters. Are you using a C++ string object? In that case, my solution works:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "12345";

    s = '0' + s;

    cout << "'" << s << "'" << '\n';
}

If you're using a C-style string, which is nothing more than an array of char terminated by '\0', it's less intuitive, more awkward, and easier to get wrong:

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char s[10] = "12345";

    // Shift everything to the right by 1 to make room at the front
    memmove(s + 1, s, strlen(s) + 1);

    // Prepend '0'
    s[0] = '0';

    cout << "'" << s << "'" << '\n';
}
tux4life commented: From all suggested approaches I like these the most. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but isn't the last null that the temp points to is in the case the root->left?

It is, but in C++ all null pointers are the same. Once temp becomes null, you have no way of determining which node pointed to it. You can think of it like this (using a simple tree):

allroadsnull

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What's wrong here:

while(temp!=NULL){[...]}
temp=add;

If temp is NULL after the loop then it no longer refers to the tree in any way. So assigning add to temp will accomplish absolutely nothing when insert() returns.

This was actually a stumbling block for me when I first started learning referential data structures. A null pointer isn't a part of the structure, and as soon as you set your reference into the data structure to null, you're done with it. To insert a node where a null currently resides, you must have a reference to the previous node:

while (true) {
    if (temp->item >= add->item) {
        if (temp->left == NULL)
            break;

        temp = temp->left;
    }
    else {
        if (temp->right == NULL)
            break;

        temp = temp->right;
    }
}

if (temp->item >= add->item)
    temp->left = add;
else
    temp->right = add;

There are a number of ways to do it, of course, but the above highlights the fact that as soon as temp becomes null, you're screwed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you're too lazy to figure out what project you want to do, the project will be stillborn because you're clearly too lazy to actually do the project.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How can I calculate CLOCKS_PER_SEC.. It is defined as 1000 in ctime. I don't want it defined. I want to calculate the actual value..

CLOCKS_PER_SEC is a standard macro, you can ignore it if you'd like, but you shouldn't redefine it.

So what is CLOCKS_PER_SEC and why is it defined as 1000? How can I calculate it?

CLOCKS_PER_SEC is the number of units calculated by std::clock() over the span of one second. std::clock() is defined as such:

"The clock function returns the implementation’s best approximation to the processor
time used by the program since the beginning of an implementation-defined era related
only to the program invocation."

As a concrete example, one of my simple C standard libraries implements clock() as this:

/*
    @description:
        Determines the processor time used.
*/
clock_t clock(void)
{
    return _sys_getticks() - __clock_base;
}

Where __clock_base is a static object initialized to _sys_getticks() at program startup, and _sys_getticks() is defined like so:

/*
    @description:
        Retrieves the process' startup time in clock ticks.
*/
long long _sys_getticks(void)
{
    return GetTickCount64();
}

GetTickCount64() is a Win32 API function that returns the number of elapsed milliseconds since system startup, which means for this implementation clock() returns milliseconds since program startup, and CLOCKS_PER_SEC is the number of milliseconds in a second (ie. 1000).

I'm trying to run a function every actual tick.

Define "tick". Apparently the tick of std::clock() isn't sufficient, and neither is the …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In lines 75-79, you unconditionally delete the head if it's the only node in the list. What if id != head->st.id in that case? As for successfully deleting the first node when it matches the id, consider adding another clause between lines 79 and 80 that handles a true deletion of a matching head:

else if (id == head->st.id)
{
    tmp = head;
    head = head->link;
    delete tmp;
}

This will reseat the head to the 2nd node in the list, and then release memory for the old head.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But I think it happens even to more experienced people, don't you agree?

Yup, though more experienced people tend to welcome others pointing out such mistakes.

On the other hand, interesting enough that you felt like giving me a lesson instead of simply posting the correct way.

I didn't give you a lesson, I pointed out that your code suggested a distinct lack in your understanding of leap years. Thus I recommended you do some more research. And you'll notice that I did post the correct way, though it was in response to the OP rather than you.

I wonder if it is related to my answers to you by now.

I won't deny that the likelihood of someone responding in an entertaining way affects how I choose to phrase my posts. :D

Hmm... I am wondering what you refer to here? That's because I have no idea what you meant there.

I meant that you made an unwarranted assumption (some might even call it stupid) and gave a common example of another assumption that's equally annoying.

Nevertheless, this conversation gets way out of the subject, don't you think?

The question has been answered. We won't know if the OP needs more help until/if he replies.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

deceptikon, what would be a legitimate keylogger, can you explain what you mean?

Parental control comes to mind, as does corporate activity monitoring, auditing for data entry employees, real-time system recording for backup and replay, and any number of research applications. Moral implications aside, these are all legitimate and legal uses of a keylogger.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your findMin() has two problems, one is a bug and another is a usability problem. The bug is that you're moving the pointer ahead by j steps on every recursive call, but you're also using j as an index into the array. This is basically a guaranteed access out of bounds. Either use j to access the array, or move the pointer ahead by 1 each time:

/* Option 1: Use a static index */
int findMin(int *arr, int min, int size)
{
    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n", *(arr), min, size);

    static int j = 1;

    if (j == size){
        return min; 
    }
    else if (min > arr[j]){
        min = arr[j++];
        return findMin(arr, min, size);  
    }
    else {
        j++;
        return findMin(arr, min, size);
    }
}

/* Option 2: Adjust the pointer */
int findMin(int *arr, int min, int size)
{
    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n", *(arr), min, size);

    if (size == 0)
        return min; 

    if (min > *arr)
        min = *arr;

    return findMin(arr + 1, min, size - 1);
}

The second option is recommended because using a static variable makes your function non-reentrant. In other words, you can only find the minimum element of an array one time. Any subsequent calls will continue to increment the index. That issue with the static variable is your usability problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I still have time until 2100 when my formula will blow up. And, definitely, I am not that old to know how was in 1900. ;)

No offense, but that's the most asinine thing I've read all day.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is the benifit to classes?

They help with the organization of large projects.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Now, there is no way to esure safety, and this is a potential unsafe operation.(if the pointer tries to access data from Derived)

It's completely safe...because it won't compile. ;)

I feel i am missing something here. Why is there no way in C++ to ensure the safety in this case?

The entire concept is inherently unsafe. Why are you trying to downcast a pointer to non-polymorphic type?

The idea of polymorphism is that you have a base class reference that may or may not have a "real" type of a derived class. You can call derived class overloads through that reference without having to know what the "real" type is. Provided you only use the interface provided by the base class, you don't need any kind of special provisions for derived class objects.

If the classes aren't polymorphic then it doesn't matter what the "real" type is. You'll be slicing that object through a base class reference in all cases. No magic happens to keep you from corrupting derived class objects by pretending that they're base class objects.

myk45 commented: thanks! +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@AD: toupper() and tolower() seem to return int and not char.

That's only to support an argument of EOF (in which case EOF is the return value). If you never expect to pass EOF, such as when it's a stopping condition prior to calling toupper() or tolower(), there's no need to use int. However, your compiler might warn about a narrowing conversion, in which case a cast is justified:

// Option 1: Use int
int foo = tolower(c);

// Option 2: Cast to char
char bar = (char)tolower(c);

Usually the destination is a string, or something along those lines, so the cast is usually the desirable approach for silencing a warning you know is spurious in that specific situation.

And of course, I shouldn't leave without mentioning that the parameter type is int, but the value range is that of unsigned char or EOF. So you generally want to enforce unsigned char on the argument to account for when vanilla char on the implementation is signed:

char foo = (char)tolower((unsigned char)c);

Otherwise you might encounter a weird situation where tolower() and friends do a table lookup using a negative value and all hell breaks loose for no apparent reason. Those are tricky bugs to troubleshoot.

tux4life commented: Thanks for the correction. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Warning 4996 is the height of stupidity, so I'll hard disable it in the project settings without any hesitation. Go to your project properties, then uder C/C++->Advanced there will be an option for disabling specific warnings. Add 4996 to that list and enjoy never seeing that ridiculous warning again.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You could build the array up manually using nested explodes:

$fields = explode(',', 'Name: John, Age: 20, Phone number: 12343223');
$result = array();

foreach ($fields as $field)
{
    $kvpair = explode(':', $field);

    if (isset($kvpair[0]) && isset($kvpair[1]))
    {
        // Both key and value exist (expected case)
        $result[trim($kvpair[0])] = trim($kvpair[1]);
    }
    else if (isset($kvpair[0]))
    {
        // Only the key exists. May be an error depending
        // on the application, but a sensible default is
        // to accept it with an empty string value.
        $result[trim($kvpair[0])] = '';
    }
    else
    {
        // $field represents an empty field from the source
        // string. A sensible default is to ignore it, but
        // raising an error works too.
    }
}
broj1 commented: Nice and clean +8
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can do a simple replace on the string:

textBox.Text = textBox.Text.Replace("Yes", "NO")

Changing the color is a different matter. I assume you want to change only the replaced text to red, which won't work unless you're using a rich text box. If it's just a regular text box then you're limited to a global foreground color change. But that can be done by changing the ForeColor property:

textBox.ForeColor = Color.Red

For a rich text box it's a bit more complicated, but you can search for substrings with that control, select them, and then set the color for the selection to red. See the documentation for details.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, you're probably screwed. Consider using source code version control in the future. As a last ditch effort, you can check your autorecovery backup files for the project. It depends on your OS, but the folder is under your documents. For example, on my Windows 7 machine it's:

C:\Users\jdaughtry\Documents\Visual Studio 2010\Backup Files

I wouldn't get your hopes up if I were you though.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's just a coincidence.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i just ask how can i do that program ?

Please read our rules concerning homework, then ask a specific question.

By the way, "How do I do it?" is silly and unproductive because obviously the answer is you think about the problem, devise a solution, and write code to implement the solution.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And I suppose you were hoping someone would tell you how to do it? Maybe even do it for you? Sorry, but here on Daniweb we expect a modicum of effort from you, so you'll generally get little sympathy for playing the clueless card.

Given your previous threads, I find it difficult to believe that you aren't able to write a simple loop, take string input, or figure out how to change the case of a single character. Hell, you could write an empty program with some comments on the requirements just to get a starting point:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    // Read a string
    // Loop over the string
    //     - Replace each character with its lower case equivalent
}

That's really all this program is.

So...please try again, and come back when you have something to show for your effort. I'll be happy to answer pointed questions, but "I don't know anything" is both too broad of a subject for me to cover concisely and it discourages me from helping you because you come off as a time vampire.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

C++ conversion of this C snippet for a simple interactive menuing system.

The code shows three files:

  • menu.h: The header file for the menu class.
  • menu.cpp: Implementation of the menu class.
  • main.cpp: A sample driver that uses the library.

The menu library is fairly generic in that you can provide a format string of menu options and possible matching input values. See main.cpp for an example of how to use it. Note that C++11 features are used in this code.

mike_2000_17 commented: Cool! +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It seems that the only reason it was deleted was out of fear of offending riahc3.

Agreed. Since no rules were broken, I'll chalk it up as a lapse in judgment (mods are human, after all) and restore the post.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

do you mean that code

No, I mean this code:

printf("\nreal number:");
scanf("%d",&x.real);
printf("\nImaginary number:");
scanf("%d", &x.imag);

There's no guarantee that you'll see "real number:" before scanf() blocks for input, which means the user will have no clue what the program is waiting for. If you're not ending the prompt with a newline, I'd recommend calling fflush() to ensure that the prompt will be visible at the right time:

printf("\nreal number:");
fflush(stdout);
scanf("%d",&x.real);
printf("\nImaginary number:");
fflush(stdout);
scanf("%d", &x.imag);

why this happened????????

Probably because you're mixing single character input with formatted input. They don't mix well. To see exactly what characters are being processed, just output ch immediately after scanf() returns. I'm willing to bet you'll be surprised.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I was going to post this in a thread, but it turned into something a bit more serious and may be useful as a code snippet.

The code shows three files:

  • menu.h: The header file for the menu library.
  • menu.c: Implementation of the menu library functions.
  • main.c: A sample driver that uses the library.

The menu library is fairly generic in that you can provide a format string of menu options and possible matching input values. See main.c for an example of how to use it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

erm i'm using the compiler in quincy 2005?

Quincy is an IDE, not a compiler. It uses MinGW as a back end, which basically amounts to the GCC compiler. GCC supports C99 under that version, as far as I can tell, but you have to turn it on with a switch. I doubt it's turned on by default, so there you go.

Line 19 - scanf("%c",&ch);
This is overkill (reason).

That's a good reason, but I think I can make it more clear how much work is done. This link is an implementation of fgetc() that I wrote (where fgetc() is the back end to getchar()); it's about 10 lines of straightforward and efficient code. Even if you include the definition of fillbuf(), the whole thing comes in at under 50 lines.

This link is the implementation for scanf(), and this link is the format string parsing helper. I'd estimate that all totaled up you're looking at close to 900 lines of code, and it's not exactly trivial. I spent more time writing printf() and scanf() than the rest of the standard library in that project put together. Naturally not all of it will be hit for a simple format string like "%c", but scanf() is undeniably a heavy function compared to getchar().

tux4life commented: Good post. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In the book called gnu c manual I read that the following code has an undefined behavior i = ++i + 1; Because since the variable i is modified more than once between the sequence point,it is not sure that what value will 'i' have.

That's correct.

But it is evident that the final value in 'i'(if i=1) would be 3.

It's not evident at all. Just because you can't think of a way the result could be anything other than 3 doesn't mean there isn't a way, or that a compiler won't handle things differently than you expect. In the case of the increment operator, it's only guaranteed that the write happens before the next sequence point. If that write is delayed until after the addition of 1 to i, you'll get a result of 2:

; Conforming assembly code for i = ++i + 1
mov r1, i
inc r1
mov r2, 1
add r1, r2
mov i, r2
mov i, r1 ; Oops, the write for ++ was not where you expected

This is quite different from the evaluation you were expecting that produces a result of 3:

; Conforming assembly code for i = ++i + 1
mov r1, i
inc r1
mov i, r1 ; The write for ++ is were you expected
mov r2, 1
add r1, r2
mov i, r2

Both are perfectly valid ways a compiler might generate machine code according to the rules …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
Begginnerdev commented: Love LMGTFY +6
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I try to understand any person I'm communicating with, figure out their native language and country of origin, level of education, perhaps even religious and political beliefs.

Only then can I offend them as efficiently as possible. :D

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if(ch==69||ch==101)
else if(ch==81||ch==113)

What do 69 and 101 mean? What do 81 and 113 mean? If you force me to memorize ASCII/Unicode or go to asciitable.com to figure out your code then your code is bad. Use the character literals that correspond to what you want, it makes the code much clearer:

if (ch == 'E' || ch == 'e') {
    ...
}
else if (ch == 'Q' || ch == 'q') {
    ...
}

You can also use toupper() or tolower() to make a single test:

if (toupper(ch) == 'E') {
    ...
}
else if (toupper(ch) == 'Q') {
    ...
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can use free SMTP servers such as those with Gmail.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

...seriously? I mean, come on, did you really think "Help?" would be productive in the slightest? Ask a real question.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Holes in your work history are more damning than history in unrelated fields. So yes, add that job.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I have found the solution in other websites that we have to clear the buffer and use cin.ingnore(). Does anyone tell me what does it means ??

cin.ignore() reads and discards characters. cin.ignore(80, '\n') is roughly equivalent to this loop:

{
    char ch;

    for (int i = 0; i < 80; i++) {
        if (!cin.get(ch) || ch == '\n')
            break;
    }
}

"Clearing the buffer" means removing pending characters in a line. The reason a line is important is because input from std::cin is nearly always line oriented. You can safely assume that by discarding characters up to and including a newline, that basically ensures that the next character request will force the user to type something.

And also what actually getline() does ?

Really all it does is read characters from the stream up to end-of-file or the specified delimiter and appends them onto the supplied string. A greatly simplified facsimile might look like this:

istream& mygetline(istream& in, string& s, const char delim)
{
    char ch;

    s.clear();

    while (in.get(ch) && ch != delim) {
        if (s.size() == s.max_size()) {
            in.setstate(ios::failbit);
            break;
        }

        s.push_back(ch);
    }

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

Sorry, couldn't get my CodeBlock IDE to work, so I did it on the ideone.com C compiler.

It'll obviously work, but it's kind of silly. printf() offers a better way to do it, and if you're just printing a string with no replacements then puts() or fputs() would be a better solution anyway:

puts("How are you %dad%");