Narue 5,707 Bad Cop Team Colleague

But what happened to operator precedence?

Your parentheses aren't changing anything, the precedence of (i=15)||(j=26) is identical to i=15||j=26 . Short circuiting rules here, so if i=15 evaluates to true, the latter half of the expression is skipped.

Narue 5,707 Bad Cop Team Colleague
Narue 5,707 Bad Cop Team Colleague

Now adding a const in my operator+(PNVector) (i.e. operator+(const PNVector &rhs) fixed this issue and I fail to grasp why.

Long story short, you were trying to bind a temporary object to a non-const lvalue reference (not legal). Temporaries may be bound to a const lvalue reference, which is why adding const fixed the problem.

Narue 5,707 Bad Cop Team Colleague

Q1. What is your name and job profile (like Database Administrator, Programmer etc.)?

List me as anonymous. My job profile is software architect (enclosing all parts of development from requirements gathering to deployment and maintenance). I also act as a consultant for IT and development staff in a wide range of fields.

Q2. How often do you write each day a week?

Very often.

Q3. How important is what you write to the successful performance of your job?

It's critical.

Q4. Is writing important to your promotion/career? How?

I fail to see how this is a different question from Q3.

Q5. What are the different types of writings you do (like names of reports you make, other documents you write)?

Correspondence with clients, partners, and vendors makes up the lion's share of what I write. I also write documentation, training materials, press releases, and such.

Q6. What would be a major fault in a piece of writing in your profession?

Lack of clarity.

Q7. What are the features of writing that you look for in someone’s writing and strive for in your own?

A certain measure of polish that says "professional and trustworthy". Sloppy writing suggests sloppiness in other areas, and being sloppy doesn't help me win any contracts. ;)

anirudh33 commented: helpful and well written +0
Narue 5,707 Bad Cop Team Colleague

Try restarting b at 1 for every iteration of the outer loop. And instead of one loop counting to 5, consider using two loops: one counting up to 3 and one counting down from 2.

Narue 5,707 Bad Cop Team Colleague

I have to use Turbo C++ due to our school syllabus.

I don't care. If you have to use it, you have to use it, but people are still going to complain that you're learning how to use an environment that's utterly useless outside of your school.

And isn't any other method for doing this like use of arrays etc. without using no. lib.?

You specifically rejected complex methods. Use of arrays constitutes duplicating the effort of an arbitrary length math library, which falls under "complex methods" far more than using a library in the first place. You can certainly implement your own big number class, but it's not trivial.

Narue 5,707 Bad Cop Team Colleague

compiled using Turbo c++ 3.0 compiler

Have you considered dropping that ancient piece of shit and switching to a compiler that isn't twenty years old and severely limited under modern architectures?

it can't find the factorial of no. grater than six

If this were true I would be confused, but your algorithm is correct and works for values of N greater than six. However, factorials grow at an insane rate, and despite using long double to counteract that growth, you're still going to exceed limits (thus invoking undefined behavior) very quickly.

If you want arbitrarily large factorials, you need some kind of big number library such as GMP.

Narue 5,707 Bad Cop Team Colleague

The standard library equivalent can be found in the <time.h> header (or <ctime> for C++). But being used to Java's Date and Calendar classes, you'll probably find the interface either quaint or woefully inadequate.

p.s. I fairly recently posted a code snippet for for the beginnings of a date_time class that may be closer to what you're used to.

Narue 5,707 Bad Cop Team Colleague

You're reading two characters, not testing the first one twice. Consider this instead:

if (isspace(ch = fgetc(txt_file)) || ispunct(ch))
    ++word_match;

Also keep in mind that while C allows you a great deal of freedom in structuring elements, taking advantage of that freedom is not always a good idea. Your code would be better written like so for readability purposes:

ch = fgetc(txt_file);

if (isspace(ch) || ispunct(ch))
    ++word_match;
Narue 5,707 Bad Cop Team Colleague

When a vector is declared to have a certain number of things such as you init it to size(10000) it's very inefficient to init it with a for loop

When the vector is already resized, using a loop to initialize is no different from using a loop to initialize an array. ZeroMemory() or memset() might be faster, but they gain that speed at a cost: throwing away type information and writing bytes in the most efficient manner possible.

The problem with this kind of optimization is many types don't facilitate that kind of type punning. This case is one of them, because memset() fills in all bytes of the object with 0, and that's not required to be an equivalent representation of 0 for type double.

The recommendation for low level stuff like memset(), bzero(), and ZeroMemory() is to restrict usage to arrays of the built-in integer types or POD aggregates of integer types. Anything else, including pointers, is unsafe.

Now for the real kicker: all of this is moot because std::vector's resizing constructor looks like this (simplified for posting):

vector(size_type n, const T& value = T());

When creating a sized vector with the constructor using only the size argument, all of the elements are initialized to the default value for their type. No further initialization is necessary:

std::vector<double> v(5); // All elements initialized to 0.0
Narue 5,707 Bad Cop Team Colleague

in that tutorial it says somewhere "Now run the program, adding command line parameters:"
how exactlty you do that?

Do you know how to use the command line? When you type the "command", that's the program name. Any whitespace separated strings after that (using double quotes for embedded whitespace) are subsequent arguments. For example:

$ echo "boogity boogity boo!"

echo is the program (the first argument), and "boogity boogity boo!" is the second argument. Here are a few more examples with the arguments extracted as the C runtime would handle it:

$ ls

argc: 1
argv[0]: "ls"(approximate)
argv[1]: NULL

$ ls -l

argc: 2
argv[0]: "ls"(approximate)
argv[1]: "-l"
argv[2]: NULL

$ ls -R /

argc: 3
argv[0]: "ls"(approximate)
argv[1]: "-R"
argv[2]: "/"
argv[3]: NULL

Most IDEs will support providing command line arguments as a debugging option, but it's best to understand using the command line directly first.

Narue 5,707 Bad Cop Team Colleague

i say this because using time as a seed, rand() generates the same number for like 2-3 seconds then changes .. causing me a problem...

That's user error. You're probably doing something like this:

int get_random()
{
    srand((unsigned)time(0));
    return rand();
}

It may be less obvious than that, of course, but the underlying problem is constantly reseeding the generator rather than doing it once (or very infrequently).

I'll take a moment to suggest this article on using rand().

Narue 5,707 Bad Cop Team Colleague

Boost.Random would be a good start. Just because rand() doesn't work for you doesn't mean you should write your own version that's better (you'd likely end up with something worse). There are many existing random number generators out there.

i have tried using rand() but i dont like it because the best seed is the time

That's not really an artifact of the generator. What do you think would be a better seed?

and it doesnt generate numbers random enough

I'd love to hear how you determined this. Not that it's an incorrect statement, but a lot of people think rand() is insufficient through hearsay rather than proper testing.

Narue 5,707 Bad Cop Team Colleague

i ask this cuz i'm not sure if it's worth learning to use command line arguments or not

Command line arguments are very simple and worth knowing. For example:

#include <iostream>
#include <string>
#include <vector>

int main(int argc, char *argv[])
{
    // Store the arguments in a more convenient data structure
    std::vector<std::string> args(argv, argv + argc);

    ...
}

The arguments correspond exactly to what's typed into the console, which means there's a caveat that args[0] will be the program name in some form[*]. That's really all there is to it. You can quibble about the nuances of the argc and argv parameters, but there's little point in doing so, in my opinion. ;)


[*] "Some form" means it could be an empty string if the program name isn't available, or it could be a full path, or a relative path, or even just the executable name (to list some common results).

Narue 5,707 Bad Cop Team Colleague

I believe Narue has graciously answered your questions/concerns.

Not completely, as my example doesn't exactly match the OP's definition of a word or handle words split across two strings. But it's a very strong base to start from.

Imo, when using fgets(), make it 1/3rd larger than your biggest line of text

Or put in a little more effort to accept arbitrary length strings.

Memory isn't that precious

Memory is rarely so precious that you can sacrifice clarity for memory savings. But wasting memory for a false sense of correctness is generally a bad idea. If you're not working with a fixed format, assumptions about line length are a point of failure.

Narue 5,707 Bad Cop Team Colleague

I haven't had any problems with my iPad, though this sounds like a browser issue. Do you have any alternative browser applications? I'm not familiar with the Galaxy Tab.

Narue 5,707 Bad Cop Team Colleague

Well, obviously strstr() alone won't do the job since it performs an unconditional exact match. You'll need to customize the behavior a little bit to suit your definition of a word:

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

bool is_word(int ch)
{
    return !isspace((unsigned char)ch) && ch != '\0';
}

size_t next_word(const char *src, const char *match, size_t pos)
{
    size_t len = strlen(match);
    
    while (src[pos] != '\0') {
        // Find the next word boundary
        while (!is_word(src[pos]))
            ++pos;
        
        // Check for a complete word match
        if (strncmp(&src[pos], match, len) == 0)
            return pos;
            
        // No match: skip the word
        while (is_word(src[pos]))
            ++pos;
    }
    
    return -1;
}

int main(void)
{
    const char *s = "I ask for multitasks";
    const char *match = "ask";
    size_t pos = next_word(s, match, 0);
    
    while (pos != (size_t)-1) {
        printf("[%zd]: '%s'\n", pos, &s[pos]);
        pos = next_word(s, match, pos + strlen(match));
    }

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

I bet it's the description part mucking things up. Note that clear() only clears the error flags, it doesn't discard unread characters. You can truly clear the stringstream by saying str_date.str("") :

for (i = 0; i < date.size(); i++)
      {
      str_date << date[i]; 
      str_date >> newDay;
      str_date >> newMonth;
      str_date >> newYear;
      apptDay.push_back(newDay);
      apptMonth.push_back(intMonth);
      apptYear.push_back(newYear);
      str_date.clear(); // For good measure
      str_date.str("");
      }
Narue 5,707 Bad Cop Team Colleague

And how are the strings formatted? God, this is like pulling teeth. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

How did you clear the stringstream? Can you post a more complete example?

Narue 5,707 Bad Cop Team Colleague

The error is precisely as stated. The system() function expects an argument of type const char*, and std::string doesn't have an implicit conversion to that type. You need to call the c_str() member function:

system(drvPath.c_str());
Narue 5,707 Bad Cop Team Colleague

So the case is that, the label will be executed, whatever happens.

The label isn't an executable statement, it's only a tag for some position within the execution path.

So how am I supposed to execute the label, in under a certain condition, if the program will execute it anyways, despite the condition?

In the case of error paths and goto, it's usually done like this:

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

int main(void)
{
    int x;
    
    printf("Enter a number [0, 10): ");
    fflush(stdout);
    
    if (scanf("%d", &x) != 1 || !(x >= 0 && x < 10))
        goto error;
        
    printf("%d squared is %d\n", x, x * x);
    
    /* Do something to avoid executing the error path */
    return EXIT_SUCCESS;
    
error:
    /* Define a separate execution path for the goto */
    printf("Invalid input\n");
    return EXIT_FAILURE;
}
Narue 5,707 Bad Cop Team Colleague

However, the goto statement is still executed

The goto statement didn't execute. It only seems that way because your labeled statement is in both execution paths. Consider this:

#include <stdio.h>

int main()
{
    int a;
    
    a = 1+1;

    /*
    if (a!=2) {
        goto error;
    }
    */

error:
    printf("error is here\n");
    return 0;
}

You'll get the same output even though the if statement is removed entirely. The label doesn't change the flow of execution at all.

Narue 5,707 Bad Cop Team Colleague

This is the current draft of C++0x directly from the committee website.

Fbody commented: I did find that link. I thought it was. Thx. :) +13
Narue 5,707 Bad Cop Team Colleague

Then it must become 01100000.Isn't that a +ve number?Each left shift is supposed to multiply the number by 2.But that isn't happening here!

No, that's a positive number. Don't confuse bit shifting with multiplication, especially when it comes to negative quantities.

should b become 00111110 or 10111110 or 11111110(adding 1s to the left)?

That depends on whether the left hand side of the expression is signed or unsigned. If it's signed, the vacated bits are filled with the sign bit. Otherwise, they're filled with 0.

Narue 5,707 Bad Cop Team Colleague

So it's not "strictly" correct and is loosely defined, but it is part of the standard...?

Um, it's strictly correct and quite well defined. I'm not sure I understand what the problem is here aside from alternative tokens being uncommon (probably because few people know about them) and Microsoft disabling them when extensions are disabled (likely due to a belief that they'll break existing code). Actually, I do understand the problem, but that doesn't spawn entertaining conversation, does it? ;)

Interesting, I've never seen it in anything I've read.

To be fair, the only book I've seen alternative tokens seriously used in is Ray Lischner's Exploring C++.

Admittedly, I haven't read the standard, I don't have a copy of it.

The draft is freely available online, up to date, and sufficiently complete for anyone who's not trying to write a conforming compiler.

Narue 5,707 Bad Cop Team Colleague

I tried using libs but some of them seemed to do all the work for me, the others seemed to be too complicated.

How about writing your own version of those libraries? You might realize why doing all of the work for the programmer is a good thing, and/or why so much complication. :)

Narue 5,707 Bad Cop Team Colleague

but i thought that because each variable is being declared inside an if statement then it shouldn't be a problem

And after the body of the if ends, the array is destroyed. The code you posted does nothing but create an array, initialize it, and then destroy it.

Narue 5,707 Bad Cop Team Colleague

Holy moly. Might I recommend reading up on variable scope and lifetime?

Narue 5,707 Bad Cop Team Colleague

Can do.

Narue 5,707 Bad Cop Team Colleague

There is no "or" operator.

Actually, there is. It's part of the alternative tokens. Though they're not often used, and some compilers (such as Visual C++) disable the keywords by default. As an alternative, <ciso646> defines them as macros rather than keywords.

Narue 5,707 Bad Cop Team Colleague

The left hand side of an expression doesn't carry over, so month == "dec" or "december" is translated as month == "dec" or "december" != 0 . Since "december" is never going to be a null pointer, it's essentially month == "dec" or true , which isn't very helpful. ;) What you really want is month == "dec" or month == "december" . Naturally that should apply to all of your if statements.

It would also be a good idea to use an if..else if..else chain to avoid checking all of the months after a match.

Narue 5,707 Bad Cop Team Colleague

Pointers are explicit while references are implicit and more of a synonym than an object in their own right. Here's the same code using a pointer instead of a reference:

void renameMonths(string *month)
{
    if (*month == "jan") {
        *month = "january";
    }
}

int main()
{
    string month;
    month = "jan";
    renameMonths(&month);
    cout << month << endl;
}

Notice how renameMonths() must dereference the pointer to get to the string, and the call to renameMonths() must pass the address of the object. All of this is hidden from you with references (which are typically implemented as pointers under the hood).

Now, because references are a synonym for an object, there's no way to define a reference to nothing. However, you can have a null pointer that points to nothing. So one reason why a pointer might be used instead of a reference is if you need to represent a nonexistent object.

Narue 5,707 Bad Cop Team Colleague

It works exactly as it should. You're passing month by value, so within renameMonths() "january" is being assigned to a copy. The original object in main() remains the same. To change the original object, you need to pass a reference (or a pointer):

void renameMonths(string& month)
{
    if (month == "jan") {
        month = "january";
    }
}

int main()
{
    string month;
    month = "jan";
    renameMonths(month);
    cout << month << endl;
}
Narue 5,707 Bad Cop Team Colleague

Aren't you just a lucky duck. This feature is part of the new C++0x standard as variadic templates:

#include <iostream>
#include <stdexcept>
#include <string>

template <typename ReturnType, typename... Args>
class Function_Handler {
    typedef ReturnType (*fun_t)(Args...);
protected:
    fun_t m_Function;
public:
    Function_Handler(fun_t foo) { m_Function = foo; }
    Function_Handler() { m_Function = nullptr; }

    void set(fun_t foo) { m_Function = foo; }
    void clear() { m_Function = nullptr; }

    ReturnType call(Args... args)
    {
        if (m_Function != nullptr)
            return m_Function(args...);
        else
            std::runtime_error("Function_Handler must be initialized");
            
        return ReturnType();
    }
};

int main()
{
    Function_Handler<void, double> a([](double a) {
        std::cout << a << '\n';
    });
    Function_Handler<int, int, int> b([](int a, int b) -> int {
        std::cout << a << " + " << b << " = ";
        return a + b;
    });
    Function_Handler<void, std::string, int, int> c([](std::string prefix, int a, int b) {
        std::cout << prefix << ": " << a << ' ' << b << '\n';
    });

    a.call(123.456);
    std::cout << b.call(1, 2) << '\n';
    c.call("Tada", 11, 22);
}

Prior to C++, you'd indeed have to write a case for each argument count you expect, and more than expected are just out of luck.

Narue 5,707 Bad Cop Team Colleague

What's the purpose of this program? Knowing the use cases can help greatly in figuring out what strategies would work best for locking down functionality.

Narue 5,707 Bad Cop Team Colleague

Now, would this work?

What an odd question. Why don't you write up a quick test to see if it works? If it does, then try to break it with pathological cases.

Narue 5,707 Bad Cop Team Colleague

Barring an off-by-one error in your array indexing, it works fine on my end.

Narue 5,707 Bad Cop Team Colleague

They say it is done in 2s complement form.

There are several methods of representing signed values in binary. Two's complement is one of the more common on PCs. Others include one's complement and sign magnitude.

Now won't this 2s complement of a negative number clash with an actual +ve number having the same binary representation?

No. Two's complement uses the most significant bit as a sign bit, which effectively cuts the positive range in half. If the sign bit is set, the value is negative, otherwise it's positive. This guarantees that all numbers in the range will have a unique binary representation.

Narue 5,707 Bad Cop Team Colleague
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string filename = "myfile_";
    
    for (int i = 1; i < 10; i++) {
        std::ostringstream oss;
        
        oss << filename << i;
        std::cout << oss.str() << '\n';
    }
}

Edit: My bad, I didn't realize this was the C forum. See below:

#include <stdio.h>

int main()
{
    const char *filename = "myfile_";
    int i;
    
    for (i = 1; i < 10; i++) {
        char buf[BUFSIZ];
        
        sprintf(buf, "%s%d", filename, i);
        printf("%s\n", buf);
    }
    
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

Update: After seeing all of the OP's code through a private message, I confirmed that <iostream> wasn't included in all of the files where cin and cout are referenced.

Narue 5,707 Bad Cop Team Colleague

I may start just deleting posts that fail to use code tags. :@

WaltP commented: Can we? Please? :hopeful: +17
Narue 5,707 Bad Cop Team Colleague

But that doesn't help, which is why I asked for a complete program.

Narue 5,707 Bad Cop Team Colleague

That's not a complete program...

Narue 5,707 Bad Cop Team Colleague

Can you post a short and complete program that has the error?

Narue 5,707 Bad Cop Team Colleague

Did you include <iostream>? Do you have a using directive for std

using namespace std;

or a using declaration for each standard name

using std::cout;
using std::cin;

at appropriate locations?

Narue 5,707 Bad Cop Team Colleague

The "new" doesn't execute until absolutely necessary.

That would be difficult to implement in any useful manner. Perhaps you're thinking of lazy initialized objects? That has the behavior you're talking about, but it's a part of the class implementation rather than the compiler.

Narue 5,707 Bad Cop Team Colleague

What have you done so far?

Narue 5,707 Bad Cop Team Colleague

I don't know "I'm SOL" mean

It means shit out of luck. In other words, you can't do what you want.

But in my opinion, if EXIST a tool to write this plugin, I think It will be easy.

A tool doesn't exist, you would have to write the plugin yourself.

Narue 5,707 Bad Cop Team Colleague

Adak suggested one algorithm, but it's somewhat inefficient. Consider two pointers (or indices) into the string. One of them is the end of your result and the other walks along the original string and skips over hyphens. This is a common algorithm for removing whitespace, but it can be specialized to hyphens or even generalized:

char *remove_all(char *s, const char *match)
{
    char *start = s;
    char *p;
    
    for (p = s; *s != '\0'; s++) {
        if (strchr(match, *s) == NULL)
            *p++ = *s;
    }
    
    *p = '\0';
    
    return start;
}