Narue 5,707 Bad Cop Team Colleague

Do I need to use cin.get() after each use of cin?

That's the most naive way of dealing with the issue. The problem is that cin's >> operator may leave a newline character on the stream for getline (or the sibling get) to terminate immediately on. Ideally you would read all input as a full line and then parse accordingly. For example:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

struct car { char make[20]; int year; };

template <typename T>
bool get_input(istream& in, T& value)
{
    string line;

    return getline(in, line) && istringstream(line)>> value;
}

int main()
{
    int cars;
    cout << "How many cars do you want to catalog? ";
    get_input<int>(cin, cars);
    car *autos= new car[cars];
    int i = 0;
    while (i < cars)
    {
        cout << "Car # "<< i + 1 << endl;
        cout << "Please enter the make: ";
        cin.getline(autos[i].make, 20);
        cout << "\nPlease enter the year: ";
        get_input<int>(cin, autos[i].year);
        i++;
    }
    cout << "Here is your collection: ";
    int j = 0;
    while (j < cars)
    {
        cout << autos[j].year << " " << autos[j].make <<endl;
        j++;
    }
    delete [] autos;
    cin.get();
    cin.get();
    return 0;
}
osirus0830 commented: Thanks so much +1
Narue 5,707 Bad Cop Team Colleague

I think that's quite enough from all of you.

Wesleyy, your question would be better suited to the Windows Software forum, but rather than move this growing flame fest, I think it would be better for you to create a new thread in the appropriate forum (using lessons learned from this one) and try again.

Narue 5,707 Bad Cop Team Colleague

Since you have no qualms about reading the file multiple times, just go through it once more character-by-character to grab the whitespace and non-whitespace counts. Then you'd have three loops:

  1. Read line-by-line and increment the line count
  2. Read word-by-word and increment the word count
  3. Read character-by-character and increment the space/non-space count

Though the typical approach to this is reading the file character by character and using a state machine to help out with the trickier blocks (ie. words). This way you only read through the file one time.

>while (!file.eof())
This is a bug waiting to happen. eof() only returns true after you've tried and failed to read from the stream, which means the last record will be processed twice. I strongly recommend using your input method as the condition:

while (getline(file, s1)) {
while (file >> s1)) {

Both getline and operator>> return a reference to the stream object, which has a conversion path to bool for checking if the state is good or not.

>ch_spaces += s1.size();
This doesn't do what you think. The length of s1 includes both whitespace and non-whitespace. You need to further break it down.

Narue 5,707 Bad Cop Team Colleague

Don't panic...i am back to help you all...
n2=(++n1)+(++n1)
See the concept is that ++n1 is preincrement operator having greater priority so it will first increment n1 value and making it 3.....
n2=(++n1)+(++n1)
++n1 is preincrement operator so it will be incremented to 4....
Now the above code is similar as...
n2=4+4;
resulting 8 as answer....

In the next statement it is similar....and the output is 15 not 13 as you mentioned....

*sigh*

I recognize that the concept of undefined behavior is somewhat confusing, especially when modern languages don't lean on undefined behavior nearly as much as C and C++. But just because you can come up with one viable way to interpret the expression doesn't mean that's the only way. The very reason it's undefined is because there are multiple equally good ways to evaluate the expression, and the standards committee didn't want to lock compilers into one method when another might be more efficient on the target platform.

Narue 5,707 Bad Cop Team Colleague

However, when you don't need random-access, i.e., you are just traversing the vector from start to finish, then, if you use the iterator version, and you later realize that you could use another container instead of a STL vector, and that new container might not be random-access, then you won't have to change anything.

To be fair, that's not a common occurrence. I've been writing C++ for nearly two decades now (above average code, in my opinion), and not once have I needed to completely swap the originally chosen container class with a different one.

There's one case where I prefer using an index over an iterator during sequential access, and that's when I need the index for other purposes than direct access:

for (T::size_type i = 0; i < cont.size(); i++)
    out<< i <<": "<< cont[i] <<'\n';

Iterators can be used for this, but I don't think it's quite as clear:

for (T::const_iterator i = cont.begin(); i != cont.end(); ++i)
    out<< i - cont.begin() <<": "<< *i <<'\n';
Narue 5,707 Bad Cop Team Colleague

im using window xp actually

I'm totally not surprised. TSRs died along with DOS. In Windows there are much better solutions, such as a Windows service. You really need to get with the times, both in choice of tools (Turbo C is ancient) and methods.

Narue 5,707 Bad Cop Team Colleague

I have been following a book named "Let Us C" by Yashavant Kanetkar.

I haven't heard good things about that particular book.

I can't find out the topic "Sequence Point Rule" in here.

That's because your book is for beginners and sequence points are a concept that isn't strictly necessary when first learning the language.

Narue 5,707 Bad Cop Team Colleague

When you exercise late you always find a reason to not to.

Like not wanting to get up early to go to the gym? :D Finding reasons not to work out is a bigger issue than timing. Regardless of when you schedule it, if you don't care enough to go, you're simply not going to go. Excuses just make you feel better, if you're the type of person who can successfully lie to themselves.

susheelsundar commented: Lol +0
Narue 5,707 Bad Cop Team Colleague

I have ran this program on my compiler DEV C++.
I also get same result=8
I have compiled many times...and It shows same output...

The problem with undefined behavior is that it's 100% unpredictable. The results could be intuitive or not. The results could be consistent or not. It could run perfectly for a year, then blow up when you're demoing your program to someone who wants to buy it. It could blow up immediately, then magically start working when you try to troubleshoot.

The lesson here is do not invoke undefined behavior.

So there is specific thing is going wrong...

Yes. What's wrong is no longer bound by the rules of C++ and can behave however the author of the compiler chose to handle such expressions, or if the author did not explicitly handle such expressions, whatever behavior falls out of the compiler's expression logic.

Can you explain more about "sequence point rule"...or give some good reference?

http://en.wikipedia.org/wiki/Sequence_point

Narue 5,707 Bad Cop Team Colleague

you may look into the cin.good(), cin.bad(), and/or the cin.fail() commands. I believe those could help you here

Perhaps you should do a little research on those member functions, as your suggestion is completely nonsensical.

Narue 5,707 Bad Cop Team Colleague

Pointers are very consistent in their behavior. Your problem can be simplified by removing a level of indirection:

void changePTR(int p)
{
    p = 100;
}

int main()
{
    int p = 1;

    cout<< p <<'\n';
    changePTR(p);
    cout<< p <<'\n';
}

Since p is passed by value (ie. changePTR is working with a copy of the value), any changes to p inside changePTR affect the copy and not the original object. To modify the original object you need to get a reference to it with another level of indirection:

void changePTR(int *p)
{
    *p = 100;
}

int main()
{
    int p = 1;

    cout<< p <<'\n';
    changePTR(&p);
    cout<< p <<'\n';
}

Now let's add a level of indirection and make p itself a pointer in main. The same issue exists because pointers are passed by value just like ints, and the solution is the same. Add a level of indirection to get a reference to the original object:

void changePTR(int **p)
{
    *p = 0;
}

int main()
{
    int i = 1;
    int *p = &i;

    cout<< p <<'\n';
    changePTR(&p);
    cout<< p <<'\n';
}
wildplace commented: still confuse on my materials.. but he helped me out =D cool guy +2
Narue 5,707 Bad Cop Team Colleague

The standard says that angle brackets cause the compiler to look in an implementation-defined location and double quotes cause the compiler to look in an implementation-defined location. I can see how there might be confusion. ;)

Traditionally the angle brackets searched the compiler's include locations followed by local directories, while double quotes did the opposite. Best practice has been to use angle brackets for compiler provided headers and double quotes for everything else.

Narue 5,707 Bad Cop Team Colleague

However it doesn't say if a similar strategy is used in case of multilevel inheritance

While there is an adjustment involved for multilevel inheritance in the case of casts, the thunk solution isn't needed and would be too heavy. For example:

struct Top { int a; };
struct Middle: Top { int b; };
struct Bottom: Middle { int c; int d; };

int main()
{
    Top *p = new Bottom;
}

In the typical implementation of single inheritance, new levels are simply appended to the object. So the object pointed to by p would look something like this:

-----
p -> | a |
     -----
     | b |
     -----
     | c |
     | d |
     -----

To access each of the data members below the top-level base you'd need a cast to force visibility, and that cast involves an offset to the appropriate sub-object:

p->a = 0;
((Middle*)p)->b = 1;
((Bottom*)p)->c = 2;
((Bottom*)p)->d = 3;

The adjustment upon casting is equivalent to adding an offset corresponding to the size of the object stack above the object you're casting to, followed by an offset into the object to get to the specified data member:

const int _Top_offset = sizeof(Top);
const int _Middle_offset = sizeof(Middle);

const int _Top_a_offset = 0;
const int _Middle_b_offset = 0;
const int _Bottom_c_offset = 0;
const int _Bottom_d_offset = sizeof(int);

*(int*)(((char*)p + 0) + _Top_a_offset) = 0;
*(int*)(((char*)p + _Top_offset) + _Middle_b_offset) = 1;
*(int*)(((char*)p + _Middle_offset) + _Bottom_c_offset) = 2; …
thelamb commented: Refreshing to have these kinds of questions/answers +3
Agni commented: Excellent explanation. Thanks +4
Narue 5,707 Bad Cop Team Colleague

My interpretation of this is that comments are handled BEFORE macros like #if. Comments are parsed first and turned into whitespace. Thus the /* and */ take precedence over #if and #endif.

That's my interpretation as well, except from the standard's specified phases of translation instead of Wikipedia.

VernonDozier commented: Point taken. I'll source better in the future. +13
Narue 5,707 Bad Cop Team Colleague

can I have the source code in c
its due today!!!!!!!!!

I think you picked the wrong user name, my friend.

Narue 5,707 Bad Cop Team Colleague

These functions stem from the guideline that data members should be kept private to avoid losing control over your data. For example:

#include <iostream>
#include <string>

class CellPhone {
public:
    std::string number;
    
    CellPhone(const std::string& number): number(number) {}
};

int main()
{
    CellPhone myPhone("555-123-4567");

    std::cout<< myPhone.number <<'\n';
    myPhone.number = "Haha, this isn't a phone number";
    std::cout<< myPhone.number <<'\n';
}

All hell can break loose when you expose a class' state for any use, so the usual advice is to make such data members private:

class CellPhone {
private:
    std::string number;
public:    
    CellPhone(const std::string& number): number(number) {}
};

Now the issue becomes accessing the data at all. In making number private, it becomes completely inaccessible to the outside, which may not be what's wanted. Perhaps we want the outside world to see it but not change it. This could be a use for a getter:

class CellPhone {
private:
    std::string number;
public:    
    CellPhone(const std::string& number): number(number) {}

    std::string Number() const { return number; }
};

int main()
{
    CellPhone myPhone("555-123-4567");

    std::cout<< myPhone.Number() <<'\n';
}

The data member is exposed, but read-only. You might also want to support modification, but still want to maintain enough control to avoid chaos. For example, validating the new phone number. This is the purpose of a setter:

class CellPhone {
private:
    std::string number;
public:    
    CellPhone(const std::string& number): number(number) {}

    std::string Number() const { return number; }

    void Number(const std::string& newNumber)
    {
        if (!ValidPhoneNumber(newNumber))
            throw std::invalid_argument("Invalid phone number");

        number = newNumber;
    }
};

int …
Dexxta27 commented: Great use of examples +0
thelamb commented: Excellent post +3
Narue 5,707 Bad Cop Team Colleague

Python is designed to be friendly and concise, though for this problem I wouldn't say that C++ fares too badly in the comparison:

#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <functional>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace jsw {
    template <typename To, typename From>
    To lexical_cast(const From& rhs)
    {
        std::stringstream conv;
        To result;

        if (!(conv<< rhs && conv>> result))
            throw std::runtime_error("Bad lexical_cast");

        return result;
    }

    template <typename T>
    std::vector<T> split(const std::string& src, char delim)
    {
        std::istringstream splitter(src);
        std::vector<T> result;
        std::string field;

        while (std::getline(splitter, field, delim))
            result.push_back(jsw::lexical_cast<T>(field));

        return result;
    }

    template <typename T>
    std::string join(const std::vector<T>& src, char delim)
    {
        std::string result;

        for (std::vector<T>::size_type i = 0; i != src.size(); i++) {
            result += jsw::lexical_cast<std::string>(src[i]);

            if (i != src.size() - 1)
                result += delim;
        }

        return result;
    }
}

namespace {
    struct random_lotto {
        int operator()() { return 1 + rand() % 49; }
    };
}

int main()
{
    using namespace std;

    typedef vector<int> pick_t;
    typedef vector<pick_t> pick_list_t;

    ifstream in("test.txt");

    if (in) {
        pick_list_t lotto_picks;
        string line;

        // Get the lottery picks from file and extract into a convenient testing format
        while (getline(in, line)) {
            lotto_picks.push_back(jsw::split<pick_t::value_type>(line, '-'));
            sort(lotto_picks.back().begin(), lotto_picks.back().end());
        }

        pick_t winning_numbers;

        // Generate this week's winning numbers
        srand((unsigned)time(0));
        std::generate_n(std::back_inserter(winning_numbers), winning_numbers.size(), random_lotto());

        bool good_input = false;
        string opt;
        function<bool(int)> counter;

        // Do a linear or binary search based on user input
        while (!good_input) {
            cout<<"Search for winners with (L)inear or (B)inary search: ";

            if (!getline(cin, opt) || …
TrustyTony commented: Thanks for sharing your knowledge! +13
Narue 5,707 Bad Cop Team Colleague

const char *msg is a pointer to const char. char* const msg is a constant pointer to char. In the former case the object being pointed to is const and cannot be modified, but the pointer can be changed to point to another object. In the latter case the pointer is const and cannot be pointed to another object, but the object being pointed to may be modified.

A third case could be where both are const:

const char* const msg;
vedro-compota commented: +++++ +1
Narue 5,707 Bad Cop Team Colleague

pls go thro the code whatever i have replied u..

Yes, let's.

>using namespace std;
If you're going to have a using directive, at least refrain from placing it in the global scope.

>void main()
Here are the rules as specified by the C++ standard:

  • On freestanding implementations (eg. embedded programs and operating systems) you can return anything you want
  • On hosted implementations you must return one of the types the implementation supports

Here's the kicker: not all implementations support a void return, but all of them support an int return. The most humorous part is that standard C++ allows omission of the return statement and 0 will be assumed, so here are the two definitions of main side by side:

void main() {}
int main() {}

The only excuse void mainers had was that returning void was more concise due to the return statement. Now that excuse is gone, so why not just return int? I'm genuinely curious.

>cin >> ch;
It's generally a good idea to check input for success and handle failures accordingly.

>int i = int(ch);
This is unnecessary. char is already an integer type.

>if ( i >= 97 && i <= 122)
This is not guaranteed to work. You're assuming a specific implementation of the character set where the alphabet characters are consecutive. This is not always the case (eg. EBCDIC). The isupper function exists for a reason, it's recommended …

Narue 5,707 Bad Cop Team Colleague

I'll bet the guy has links in his signature. Spammers like to do this to raise their page rank in search engines. However, Daniweb doesn't expose signature links to search engine web crawlers, so the net effect of these spam posts is a little valueless fluff added to the thread.

It's generally not worth the effort of banning and deleting unless a signature spammer floods the forum. It's also somewhat difficult to differentiate between a legitimate member making inane comments and a sig spammer.

Narue 5,707 Bad Cop Team Colleague

I dont understand ! how could an && condition be short circuited?

If the left operand is false, there's no point checking the right operand. (false && x) is absolutely going to result in false regardless of x.

Narue 5,707 Bad Cop Team Colleague

How do you handle these types of requests?

I would require them to fill out a software request form with business justification. Then if the justification doesn't have a suitable ROI for the license and maintenance costs, that would give me a defensible position for rejecting the request.

Narue 5,707 Bad Cop Team Colleague

.. i just need the starting ..

Compiler development is quite a can of worms to be opening when you're in an intro class (and presumably very green as far as programming goes). That's why I think you're misunderstanding the assignment and need clarification from the teacher.

But if you're really interested, I'd start with BNF for defining the grammar of your simple language. And you will need to define your own language to keep this compiler simple enough, because pretty much any posted grammar out there will have an eye more toward functionality than simplicity and be harder to parse[1].

Once you have a grammar you can write code to break a sequence of input characters (the source code) into tokens for subsequent parsing. Tokenization isn't especially difficult unless you have a ton of ambiguity in the grammar, which as a beginner you'll probably have a hard time avoiding at first.

Parsing is when the tokens are given semantic meaning, and this is where the simplest grammar possible makes your life easier. Ambiguities in the grammar will make parsing exponentially harder. Unless the grammar is strictly linear[2], you'll want to look at recursive descent parsing to evaluate it. I'd strongly recommend that your first language be linear though, so you can get a feel for the parts of a compiler without making any of them especially difficult.

A compiler is technically just a program that converts one language into another. Often the destination …

Narue 5,707 Bad Cop Team Colleague

I don't understand either. Maybe you should specify what "the error" is as well as what "the input" is and what "the output" you were expecting. :icon_rolleyes:

WaltP commented: cluless, eh? +15
Narue 5,707 Bad Cop Team Colleague

To answer the other half of the question, you're not allowed to post on Daniweb if your account is banned. It's the web forum equivalent of sitting in time-out.

Narue 5,707 Bad Cop Team Colleague

This is a non-trivial program. First you need to be able to parse C code into tokens and recognize identifiers, which is a difficulty in and of itself. That would be the first step. Once you have a list of tokens, you need to determine the purpose of each identifier in the list (declaration, value context, or object context). In declarations and object contexts, that's where the value may change. In value contexts, that's where the value is referenced.

The problem is that you can reference the object without directly changing the value even though the value eventually gets changed. This is a somewhat difficult case to determine. For example:

void foo(int *p)
{
    *p = 10;
}

int main(void)
{
    int x;

    foo(&x);

    return 0;
}

x is modified through p, so *p = 10 would count as a "definition" for x in your requirements.

Another interesting difficulty is the preprocessor, which can create synonymous tokens and further hide modifications to a variable:

#define y x

int main(void)
{
    int x;

    y = 10;

    return 0;
}

This brings up the question of whether to assume the input source code has already been preprocessed, or to preprocess it yourself. Working with a preprocessed translation unit would be vastly simpler because then you wouldn't need to worry about headers, though you'd still have potential issues with external definitions and other translation units managed by the linker.

I'll go out on a limb and assume this …

Ancient Dragon commented: nice :) +36
Narue 5,707 Bad Cop Team Colleague

1. creating a loop that continuously searches all occurrences of the substring until the end of the longer string
2. replace the substring with another string

Yes, this pretty much defines the whole problem. Have you tried anything yet? I still don't see any posted attempts by you, either in C or pseudocode. What kind of help are you expecting at this point? We don't even know where you are in terms of understanding the steps involved, and as such, the only conclusion is that you've done nothing in the hopes that someone will give you the solution.

So how about you stop whining and show some effort if you want continued help.

Narue 5,707 Bad Cop Team Colleague

Dude, wtf. Just build your freaking tree. It's already sorted! You don't need a linked list, you don't need a separate sorting step:

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

struct person {
    char first_name[20];
    char last_name[20];
};

struct node {
    struct person data;
    struct node *link[2];
};

struct node *insert(struct node *root, struct person data)
{
    if (root == NULL) {
        root = malloc(sizeof *root);
        
        if (root != NULL) {
            root->data = data;
            root->link[0] = root->link[1] = NULL;
        }
    }
    else if (strcmp(data.last_name, root->data.last_name) < 0)
        root->link[0] = insert(root->link[0], data);
    else
        root->link[1] = insert(root->link[1], data);

    return root;
}

void display(struct node *root)
{
    if (root == NULL)
        return;

    display(root->link[0]);
    printf("%s, %s\n", root->data.last_name, root->data.first_name);
    display(root->link[1]);
}

int main(void)
{
    struct person people[] = {
        {"John", "Doe"},
        {"Joe", "Public"},
        {"Random", "Person"}
    };
    struct node *root = NULL;
    size_t i;

    for (i = 0; i < sizeof people / sizeof *people; i++) {
        struct node *temp = insert(root, people[i]);

        if (temp == NULL) {
            fputs("Error allocating memory\n", stderr);
            break;
        }

        root = temp;
    }

    display(root);

    return 0;
}

Do you even know what a binary search tree is?

Narue 5,707 Bad Cop Team Colleague

It returns the number of seconds since 1970

Perhaps on your implementation. Here's the specification for the time() function in its entirety:

7.23.2.4 The time function

Synopsis

1 #include <time.h>
time_t time(time_t *timer);

Description

2 The time function determines the current calendar time. The encoding of the value is
unspecified.

Returns

3 The time function returns the implementation’s best approximation to the current
calendar time. The value (time_t)(-1) is returned if the calendar time is not
available. If timer is not a null pointer, the return value is also assigned to the object it
points to.

Unspecified means the implementation can do whatever it wants as long as the choice is documented. Nowhere in the standard is "1970" or "epoch" mentioned. Further, because the representation of time_t is unspecified, the result of time() need not be in seconds. An implementor can choose to make time_t the number of Twinkies sold in the fiscal year as long as the other date/time functions behave as specified.

Ancient Dragon commented: absolutely correct +36
Narue 5,707 Bad Cop Team Colleague

C++/CLI and C# are assembly compatible. You can write an assembly in one language and reference it from the other because they're both CLR-based languages. C# can also reference native C++, but it's not as simple as referencing an assembly because the native C++ DLL would be outside of the CLR framework.

Narue 5,707 Bad Cop Team Colleague

Done. Show me yours and I'll show you mine.

Narue 5,707 Bad Cop Team Colleague

Automated language translators suck ass. No offense, but if your English is so weak that you must rely on one, it would be better to find a forum in your native language.

Narue 5,707 Bad Cop Team Colleague

I'm not sure what rock you've been living under, but smartphones have been used heavily in businesses for well over a decade. Note that the explosion of affordable laptops made IT security pros very nervous too. Technology evolves and so do the ways of using it. I think the best way to deal with the situation is coming up with ways to use the new technology instead of reasons to ban it.

As for tablets, I'm not convinced that they're mature enough to be useful except in niche areas.

Narue 5,707 Bad Cop Team Colleague

wat is d need to typecast..??/

First and foremost, function pointers and object pointers are incompatible with or without a cast. This cast is a very bad idea, and your book is likely written by an idiot unless it's showing how not to do things. To answer your question, the cast is required to compile because there's no implicit conversion from the function pointer type to int*.

Narue 5,707 Bad Cop Team Colleague

But there are hardly anyone there

If nobody hangs out there because nobody is there, nobody will continue to be there. :icon_rolleyes: Why don't you add yourself to the number of people on IRC and then the count goes up by one. Get others to do the same and the number of people will grow. I'd like to think this is obvious, but apparently only a handful really understand (the ones who already visit #daniweb).

Narue 5,707 Bad Cop Team Colleague

So, I've heard rumors that you can write web apps in C++. Is that true?

Certainly. It's really not much more than reading from standard input, doing something, and writing to standard output, with some environment variable I/O here and there. A bit of a pain in my opinion though, C++ isn't well suited to heavily string-based processing. That's why Perl has generally been the go-to for CGI in the past.

is web developing with C++ practical or should i go out of my way to learn a new language?

I've done enough web development in C++ to know that I don't care for it. Perl was easier. I'm not a fan of web development in general though, so perhaps my opinion isn't as good as someone who lives and breathes the stuff.

I think right now PHP rules, but there are quite a few options for server side web applications.

Narue 5,707 Bad Cop Team Colleague

Yay, 1 million members, with 999,000 of them being one-off posters, banned spammers, or lurkers who add no value. :icon_rolleyes: I fail to see the benefit of fluffing the member count with shit and then bragging about it.

Narue 5,707 Bad Cop Team Colleague

Bump!

I'll be happy to help you, after you explain what makes you so much more important than everyone else posting threads on this forum who got bumped down (not to mention one unlucky soul who fell off into the void of page 2 and will now never get help) so that your question could be brought back to the forefront.

Fbody commented: LOL! I love it when you tear someone a new one. :):D +5
Narue 5,707 Bad Cop Team Colleague

Without seeing your code, all I can say is that the error is on line 42.

kvprajapati commented: :) +12
Narue 5,707 Bad Cop Team Colleague

can you tell me more about it ???

Yes, but I'll give you a better option since realloc is generally not a good idea in C++. Use a std::vector object instead of an array, then you can call the resize member function.

Narue 5,707 Bad Cop Team Colleague

imgSet is a 2D array, dude. printf("%c ",imgSet[i]) isn't doing what you think it's doing.

jayzee1989 commented: good stuff +1
Narue 5,707 Bad Cop Team Colleague

Most image types have a specific format. If you insert bogus bytes into the format, it likely won't be recognized anymore. Your question is akin to "I smashed my cell phone, why doesn't it make calls anymore?". :icon_rolleyes:

jonsca commented: I find knocking my phone around helps to reseat the components to the board. ;) +7
Narue 5,707 Bad Cop Team Colleague

Can the compiler go one step further and notice that foo() will never get called and hence just delete it so we're now here?

No, and the reason is because foo has external linkage (a poor choice of defaults, in my opinion). It might be used in another translation unit, and introspection between translation units is pretty darn expensive. If you give foo internal linkage by qualifying it as static, then the compiler could potentially do something.

VernonDozier commented: Thanks. +13
Narue 5,707 Bad Cop Team Colleague

>> if(foo())

But Hello World should be displayed regardless of the return value of foo(), and the || 1 causes that. So you can't just toss out that or condition.

True. I'll blame an early morning brain fart. :D

Fbody commented: :) You're allowed one once in a while. ;) +5
jonsca commented: Regardless, I want a refund of today's ticket price ;) +7
Narue 5,707 Bad Cop Team Colleague

Before looking for ways to do this, maybe you should consider why you want to do it in the first place. Bitwise operations not working on floating-point isn't much of an issue because most of the time it's nonsensical.

vineeshvs commented: i usually get good replies from narue +1
Narue 5,707 Bad Cop Team Colleague

cout is smart about types. If you try to print a char, it will be interpreted as a character rather than a small integer. If you copy that value into an int object and print that cout will no longer interpret it as a character. You're seeing the integer value of the characters rather than the character representation.

Try changing int n0,n1,n2,n3,n4; to char n0,n1,n2,n3,n4; .

Narue 5,707 Bad Cop Team Colleague

Try creating a new thread for accepting input and manage the timeout in your main:

#include <windows.h>

namespace jsw {
    namespace threading {
        class auto_event {
        public:
            auto_event(): _event(CreateEvent(0, false, false, 0)) {}

            BOOL wait(DWORD timeout = 1) const
            {
                return WaitForSingleObject(_event, timeout) == WAIT_OBJECT_0;
            }

            BOOL set() { return SetEvent(_event); }
        private:
            HANDLE _event;
        };

        class thread {
        public:
            static thread start(
                LPTHREAD_START_ROUTINE fn, LPVOID args = 0, 
                DWORD state = 0, DWORD timeout = 5000)
            {
                return thread(CreateThread(0, 0, fn, args, state, 0), timeout);
            }

            static void sleep(DWORD milliseconds) { Sleep(milliseconds); }
            static void exit(DWORD exitCode) { ExitThread(exitCode); }
        public:
            thread(HANDLE thread, DWORD timeout): _thread(thread), _timeout(timeout) {}
            ~thread() { CloseHandle(_thread); }

            DWORD exit_code() const
            {
                DWORD exitCode = NO_ERROR;

                GetExitCodeThread(_thread, &exitCode);

                return exitCode;
            }

            HANDLE handle() const { return _thread; }
            BOOL is_alive() const { return exit_code() == STILL_ACTIVE; }
            DWORD join() { return WaitForSingleObject(_thread, _timeout); }
            DWORD suspend() { return SuspendThread(_thread); }
            DWORD resume() { return ResumeThread(_thread); }
            BOOL abort(DWORD exitCode) { return TerminateThread(_thread, exitCode); }
        private:
            HANDLE _thread;
            DWORD _timeout;
        };
    }
}

#include <iostream>
#include <string>

DWORD WINAPI get_password(LPVOID args)
{
    using namespace jsw::threading;

    std::string *s = (std::string*)((LPVOID*)args)[0];
    auto_event *e = (auto_event*)((LPVOID*)args)[1];

    getline(std::cin, *s);
    e->set();

    return NO_ERROR;
}

int main()
{
    using namespace jsw::threading;

    std::string password;
    auto_event e;
    LPVOID args[2] = {&password, &e};

    thread worker = thread::start(get_password, args);

    if (e.wait(5000))
        std::cout<<'\''<< password <<"' was correct\n";
    else {
        worker.abort(NO_ERROR);
        std::cout<<"Invalid password\n";
    }
}
Narue 5,707 Bad Cop Team Colleague

I want to know when you'll use this knowledge anywhere except in a class taught by an idiot. Yes, there are other answers, but they follow the same concept. And your code is only correct with the condition that the compiler supports a void return from main. Otherwise it invokes undefined behavior.

jonsca commented: Thus spake the Narue. Too true! +6
Narue 5,707 Bad Cop Team Colleague

What's the ultimate goal here? Are you just trying to report the uptime of a process, or is this more of a control to keep the process from running continuously for a certain amount of time?

Narue 5,707 Bad Cop Team Colleague

In other words, you're completely incompetent. Massive ideas but an inability to follow through with them makes you utterly valueless. Then again, you're very obviously a troll who has no interest in following through with massive ideas. Rather, you're simply trying to get jollies out of wasting people's time.

Saith commented: Just bc we all love trolls. +1