Narue 5,707 Bad Cop Team Colleague

There are an infinite number of function signatures.

Narue 5,707 Bad Cop Team Colleague

What value did you enter?

Narue 5,707 Bad Cop Team Colleague

If we're only talking about pass by reference vs. pass by value, then the benefit of pointers only shows up in two cases:

  1. You want to use output parameters rather than input parameters. Passing by reference enables this.
  2. The pointed-to object is relatively large compared to a pointer.

Comparing the passing of a pointer to the passing of an int or a float doesn't show the benefits of pointers because int and float are comparable in terms of size. Now if you have a composite type that amounts to several times the size of a pointer, or arrays where the size is variable and unknown, using a pointer with a small and known size is preferable.

Narue 5,707 Bad Cop Team Colleague

Educated guess: scanf("%d",a) is missing the address-of operator on a . Often this results in a miserable crash, and it's very easy to forget that it should be &a .

Narue 5,707 Bad Cop Team Colleague

Can I say the pointer char *end = a + 15 is a valid pointer?

No. The C standard states that pointer arithmetic must result in a pointer to a valid element or one past the end of the array. Any further either before the first element or beyond one past the end is undefined. You don't even have to dereference that pointer; simply calculating it invokes undefined behavior.

Narue 5,707 Bad Cop Team Colleague

the .h files are linked automatically.

Headers aren't linked at all. Do you know about the primary phases of compilation?

  1. Preprocessor: Preprocessing directives are evaluated and textually replaced within the source code. Header files are expanded, macros are replaced, etc... The result is a translation unit.
  2. Compiler: Translation units are compiled into object files.
  3. Linker: Object files are linked together into an executable.

By the time the linker runs, the headers have already been expanded into the source files that include them, with those files compiled into object code.

Narue 5,707 Bad Cop Team Colleague

You already have the match statement written. It works. All you need to do is cover both base cases and return the correct boolean value for each base.

Narue 5,707 Bad Cop Team Colleague

One use is iterators. The idea is that you have a begin iterator that points to the first valid element in the sequence and an end iterator that points to one past the final element in the sequence. Increment the begin iterator until it's equal to the end iterator (a common pattern in C++) and process the contents:

#include <stdio.h>

int main(void)
{
    char a[14] = "this is a test";
    char *begin = a;
    char *end = a + 14;

    // Iteration style using begin/end
    while (begin != end)
        printf("%c\n", *begin++);

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

Start by determining what your base case is. You have two of them:

  1. str2 is matched in str1
  2. str2 is empty

Once you have the base cases you can return the appropriate result, and then for any non-base case simply return the result of your recursive call: return find(str1, str2+1) .

Narue 5,707 Bad Cop Team Colleague

I confused why a valid pointer might not be dereferenced

It's a valid pointer alone, not a valid array element. This gives compilers the freedom to always implement one past the end as a single byte (the smallest addressable unit) and not waste space creating a full unused element of the array type.

what the one-past-the-end pointer is used for?

It simplifies iteration and size calculations.

Narue 5,707 Bad Cop Team Colleague

I really have no idea how to do it.

Not paying attention in class, then?

But this is what I have done so far

Which is to say nothing, because all of the member functions are empty. Writing the declarations doesn't really count as doing anything, much as I'd like to debate the necessity of good class interface design.

Narue 5,707 Bad Cop Team Colleague

error C2664: '_stricmp' : cannot convert parameter 1 from 'WCHAR [260]' to 'const char *'

That's a perfectly rational error. Your string is of type WCHAR and _stricmp clearly only accepts strings of char. On the assumption that you're using a compiler which supports it, try _wcsicmp instead of _stricmp.

Narue 5,707 Bad Cop Team Colleague

You shouldn't need a helper with this interface unless the algorithm is recursive. If it's recursive, a helper that takes the current node as an argument is the cleanest solution. In terms of the size member function, it's as simple as a loop (no helper or recursion needed):

size_t priority_queue::size() const
{
    if (_root == 0)
        return 0;

    node *it = _root;
    size_t n = 1;

    while (it->get_next() != 0) {
        it = it->get_next();
        ++n;
    }

    return n;
}

I'm strongly against using recursion for linear problems, so I'd recommend against using recursion in a linked list even if it weren't silly. ;)

Narue 5,707 Bad Cop Team Colleague

I think you're expecting us to be psychic. Can you provide a little context here instead of starting somewhere in the middle?

Narue 5,707 Bad Cop Team Colleague

opening the output file before the loop doesn't help at all

Ah, I see. You've got a booger of a problem in that both the streams are trying to access the same file. It's generally best not to introduce that kind of concurrency issue, or if you do, be very explicit about how you handle it:

void capital(char file1[])
{
    fstream file(file1, ios::in | ios::out);
    char line[200];

    while (true) {
        // Save the current write position
        fstream::pos_type set = file.tellp();

        if (!file.getline(line, sizeof line))
            break;

        line[0] = toupper(line[0]);

        // Overwrite the old string with the new one
        file.clear();
        file.seekp(set);

        // Be sure to flush so we can safely switch modes
        file<< line <<endl;
    }

    file.close();
    printPoem1(file1);
}
Narue 5,707 Bad Cop Team Colleague

For each line you re-open the outfile in ios::out mode. This will always overwrite the file starting at position 0. Try opening outfile once before the loop:

ofstream outfile(file1);

while (infile.getline(line,200)) {
    line[0] = toupper(line[0]);
    outfile<< line <<'\n';
}

Note that using eof() as a loop condition is a bug, you'll end up processing the last line twice. And toupper does the right thing regardless of which character you give it, so there's no need to check if it's an alphabetical character first.

Narue 5,707 Bad Cop Team Colleague

so far I seem to understand how they work "I think" at this stage

I think you're still fuzzy on the distinction between data structures and classes. It helps to think of data structures as more of an abstract concept while classes are a concrete implementation detail. A data structure is really just a pattern of storing and working with data that achieves a specific goal (eg. fast searches).

4. I guess at this point my final thoughts on data structures is that data structures would be a good way to store data that you may not "at the time" know what you may possibly want to do with later on.

On the contrary, data structures are typically selected with a very specific data usage in mind. Occasionally you'll pick a data structure that's "future-proof" and can handle a large number of use cases because you're not entirely sure how the data will react, but for the most part you'll choose from a position of knowledge.

predator78 commented: Narue really understood what I was confused about. +2
Narue 5,707 Bad Cop Team Colleague

1985 is calling, they want their code back. I'm not surprised if you're using a modern compiler and getting warnings about K&R style C.

Narue 5,707 Bad Cop Team Colleague

No copy constructor is called. Whereas it should be.

Actually, it shouldn't be. You're trying to use the copy assignment operator, not the copy constructor. A use of the copy constructor would be mymatrix c3 = c1 + c2; . Generally, if you need a copy constructor, you also need a copy assignment operator and destructor.

Narue 5,707 Bad Cop Team Colleague

Change Telegram *tele = new Telegram(); to tele = new Telegram(); in the SSBL constructor.

Narue 5,707 Bad Cop Team Colleague

I am looking for something to compact the clear and push_back in one line...

Why?

Any sugestion or idea?

Nothing built into std::vector presently supports this. You'd have to add at least one line to get rid of one line, which nets you nothing.

Narue 5,707 Bad Cop Team Colleague

Your SSBL constructor is creating a new local Telegram object called tele that hides the private member called tele. So you're not actually initializing the private member at all.

Narue 5,707 Bad Cop Team Colleague

does anyone know at what posting number it changes to the next title, and/or what all of the titles are?

Yes, and yes. But half the fun is seeing what comes next as you continue to post. :)

Narue 5,707 Bad Cop Team Colleague

Compare and contrast:

#include <iostream>
#include <fstream>
#include <time.h>
#include <stdio.h>
using namespace std;

tm *gettime()
{
    time_t rawtime;

    time(&rawtime);
    
    return localtime(&rawtime);
}

int main()
{
    cout<<  asctime(gettime());
}
Narue 5,707 Bad Cop Team Colleague

In my opinion, typed datasets cause more trouble than they're worth.

Narue 5,707 Bad Cop Team Colleague

The answer he mentioned might beby mistake he typed wrong...

Really? That's your excuse for advocating undefined behavior?

I have worked it out in over different platforms and machines and this is what i m getiing as an answer.....

You have you worked it out on every compiler and platform? Because I can prove conclusively that the C standard says it's undefined behavior and that undefined behavior may cause unpredictable results. If you need proof before admitting that programming against a standard is a good idea and ignoring the warnings of said standard is a bad idea, then I'd question your competency.

You're clearly too stubborn to see reason, so let's simply agree to disagree and let readers of the thread decide for themselves which makes more sense.

Narue 5,707 Bad Cop Team Colleague

Just don't know why you guys don't accept the way it is designed for and just tell it undefined sequence....

We do accept the way it is designed: undefined, don't do it.

Just quote me one example when ++i gave two different output.....

You gave such an example in this very thread. And I quote:

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

You say the output is 15 (presumably by testing it on your compiler), but the OP got a result of 13 on his compiler. If the result were well-defined then both compilers would agree, and print the same result.

Narue 5,707 Bad Cop Team Colleague

I think so first of all you must understand the difference between preincrement and postincrement operator...

That's really quite irrelevant. Both invoke undefined behavior when modifying an object multiple times between sequence points, in any combination.

This is only the way to run from the problem rather than finding solution to the problem....

There is no solution to the problem aside from avoiding it in the first place.

Killer.bee commented: Explain it with explanation where it gave arbitrary result to proof your words -1
jonsca commented: Unwarranted and undeserved +14
Narue 5,707 Bad Cop Team Colleague

But if i use a non-integer position counter

I fail to see how your requirement leads to needing a non-integer index.

Narue 5,707 Bad Cop Team Colleague

Well, if you need the array for other purposes then it has to be there. But if all you're doing is reading from a file and displaying the contents, you can simply pull one record at a time and not bother storing past records:

for (int i = 0; i < TILE_Y; i++) {
    for (int j = 0; j < TILE_X; j++) {
        int tile;

        reader>> tile;
        reader.ignore();

        cout<< tile;
    }

    cout<<'\n';
}
Narue 5,707 Bad Cop Team Colleague

That's fine. For extra l33t points, you can also merge the input and output loops, or even get rid of the array altogether if that's the only place you use it.

Narue 5,707 Bad Cop Team Colleague

I would have thought that using this input:

1,

with this syntax:

fin >> a[j];

where a[j] is an int would result in fin going into an error state

Nope, input simply stops at the first non-integer character. The stream state isn't affected.

I would have expected the posted syntax to work if the input had been:

1 , 0 , etc.

Actually, that would not have worked without an extra step of trimming leading whitespace before extracting the comma. Leading whitespace after the comma is fine because operator>> will skip it automatically when reading an integer. Only the bogus integer character (a comma) needs to be removed.

I would have used getline() with comma as the delimiter and then convert the input string into the desired numerical value using a stringstream

Once again, why make it harder than it needs to be? :)

Narue 5,707 Bad Cop Team Colleague

whatever happened to strtok() lol

Why complicate matters when you don't have to?


lol :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

You can't initialize an array member in the initialization list. It has to be done in the body of your constructor. If you're creating an array of a user-defined type, that type must also support default construction.

Narue 5,707 Bad Cop Team Colleague

Read an int, then ignore a single character. Optionally peek to see if the character is a comma for more robust error checking:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 4; j++) {
        if (!(in>> a[i][j]))
            break;
        in.ignore();
    }
}
Narue 5,707 Bad Cop Team Colleague

Run man od for a list of supported formats on your system.

Narue 5,707 Bad Cop Team Colleague

If you're just trying to display the result, something like this would work:

$ cat /dev/random | od -tl -w4

Remember that /dev/random is just a file. You can process it like any other file.

Narue 5,707 Bad Cop Team Colleague

I'd tell you, but then I'd have to kill you. ;)

Narue 5,707 Bad Cop Team Colleague

Using cin.get() is fine when starting out. In fact, it helps one to learn the weaknesses of stream I/O and fully appreciate the recommended guidelines down the road. ;)

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

>for (int i; i < 5; i++)
i is not initialized to anything, it's the cause of error 2. Might I suggest initializing it to 0?

>(ae.Message);
This doesn't do anything, it's the cause of error 2. Most likely you wanted to print ae.Message or log it somewhere.

Narue 5,707 Bad Cop Team Colleague

I have used your suggested method of controlling the while loop in this version of my program but actually I have not understand what is the difference between the two methods.

Your original method is a bug and my method corrects the bug. The bug is that on the very last iteration of the loop, eof() will return false even though there's nothing left to read. Then your input method will fail, which leaves the input variable with the same contents as the previous iteration. So you process the same input two times.

I think you misunderstood my use of this statement

Yes, I misunderstood your use of ch_nspaces. I read it as the number of whitespace characters rather than the number of total characters minus whitespace.

As promised, here is my version:

#include <cctype>
#include <fstream>
#include <iostream>

int main()
{
    std::ifstream in("test.txt");

    if (in) {
        int total = 0, spaces = 0, words = 0, lines = 0;
        bool inword = false;
        char ch;

        while (in.get(ch)) {
            ++total; // All characters including whitespace

            if (ch == '\n')
                ++lines;

            if (std::isspace(ch)) {
                ++spaces;
                inword = false;
            }
            else if (!inword) {
                ++words;
                inword = true;
            }
        }

        // Add the last line if it doesn't end with '\n'
        if (ch != '\n' && total > 0)
            ++lines;

        std::cout<<"Total characters ("<< total <<")\n"
                 <<"Non-spaces ("<< total - spaces <<")\n"
                 <<"Words ("<< words <<")\n"
                 <<"Lines ("<< lines <<")\n";
    }
}
Narue 5,707 Bad Cop Team Colleague

Once you have a working version of the code, I'll also post an alternative using my suggestion.

Narue 5,707 Bad Cop Team Colleague

I regard hielo's non-responsive response as an attempt to bully a newbie.

I'm sorry you feel that way, but nothing in hielo's post constitutes bullying. Your use of code tags made the code more difficult to follow (for which he suggested a fix), and frowny faces embedded in the code isn't exactly a common idiom to mark problem areas. In fact, outside of code tags, the very nature of some languages can create unintentional emoticons, so it's not unreasonable to interpret your original post as containing no real question.

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

if there is no name in an entry isnt that entry null then?

It depends, but the generally safe assumption is that the entry only contains what you explicitly store there. If you didn't initialize the entry to a null value, it's unwise to assume that an empty entry will be null.

It is in Java anyway...

C++ is not Java. Please post your array declaration so we can give you better advice on how to implement this search.

Narue 5,707 Bad Cop Team Colleague

Which one to accept?? Sequencing problem as explained by Narue or other factor as explained by sbesch?

Both are acceptable. You can think of it as the abstract vs. the concrete. My abstract view based on the C standard's rules says that your program is undefined and need not behave predictably. sbesch's concrete view based on enlightened speculation speculates how the compiler may be reaching the unintuitive result.

Narue 5,707 Bad Cop Team Colleague

almost every book is related to either .NET, Java or C++

They have books on C too. The search is godawful though, which is why I linked you to the browse page. But if it's too hard to scroll and search for C, I'm sorry.

Narue, thanx for the "link" as well as "suggestion" though.

...