Narue 5,707 Bad Cop Team Colleague

Please write up a test case and post it here. By test case, I mean something similar to that described here.

Narue 5,707 Bad Cop Team Colleague

I cannot see why this should give an error, the base class pointer reference is declared as referring to constant pointer memory.

The problem isn't about const, it's about an added level of indirection. a_t** and b_t** are incompatible types; you were expecting polymorphism to be recursive through all levels of indirection, which isn't the case.

To get a reference or pointer to a pointer to a derived class, you'd need to go through an intermediate pointer to the base class:

struct base {
    virtual void foo() { cout << "base\n"; }
};

struct derived: public base {
    virtual void foo() { cout << "derived\n"; }
};

derived* pd = new derived;
base* temp = pd;
base** ref_pb = &temp;

(*ref_pb)->foo();
Narue 5,707 Bad Cop Team Colleague

Is the particlesToRender array (assuming it's an array) being used polymorphically?

Narue 5,707 Bad Cop Team Colleague

Abstraction means Giving only essential things and hiding unnecessary details.

Implementation details are often hidden away behind a more intuitive interface in abstraction, but that's not required. Abstraction is the process of matching the representation of data or algorithms to their meaning within a program. It's a method of implementing "code for the application, not the computer".

An example of abstraction is std::map<A,B>. We only care about uniquely mapping A to B and being able to perform fast lookups of B based on A. There's really no reason to know that std::map is implemented as a balanced search tree, and we certainly don't want to worry about managing the details of a search tree when we really just want a mapping.

The std::map abstraction gives us the ability to write what we meant in terms of the application rather than lower level junk that makes the computer happy and just obscures what the application is really doing. This is abstraction.

Encapsulation means binding the data members and methods together in a capsule form to avoid accidental changes to data from external users.

Encapsulation is the bundling of related algorithms and data. It's possible (and not entirely uncommon) to use encapsulation without any kind of data hiding:

struct point {
    int x;
    int y;

    point(int x, int y);
};

struct line {
    point a;
    point b;

    line(point a, point b);
    double distance() const;
};

This bundling makes for convenient interfaces as well as simplifies the task of …

Narue 5,707 Bad Cop Team Colleague

I'm sorry, you have the wrong forum. I believe you were looking for the psychic friends forum.

Narue 5,707 Bad Cop Team Colleague

Shall we start with the fact that the standard string class is in the std namespace? You're treating it as if it's in the global namespace.

Narue 5,707 Bad Cop Team Colleague

Your personal feelings on the matter match our policies. Homework questions are fine, provided the student puts forth some effort and doesn't expect helpers to do the work. On the other side of the coin, helpers should refrain from giving away homework answers which tempts students to cheat and is counterproductive when the goal is education.

A little push is often all that's needed when it comes to providing help. My current signature embodies the attitude helpers should have: "The worst thing you can do for those you love is the things they could and should do themselves." — Abraham Lincoln

Narue 5,707 Bad Cop Team Colleague

That's not all of your code because it doesn't compile. But I'll assume that your issue was failing to qualify cin with std::

#include <iostream>

// ...

int main( int argc, char *argv[] )
{
    if( argc < 4 )
    {
        std::cerr << "Usage: " << argv[0] << " imageDimension sourceImage "
            << "targetImage" << std::endl;
        return EXIT_FAILURE;
    }

    switch( atoi( argv[1] ) )
    {
    case 2:
        LabelOverlapMeasures<2>( argc, argv );
        break;
    case 3:
        LabelOverlapMeasures<3>( argc, argv );
        break;
    default:
        std::cerr << "Unsupported dimension" << std::endl;
        exit( EXIT_FAILURE );
    }

    std::cin.ignore(1024, '\n');
    std::cin.get();
}
Narue 5,707 Bad Cop Team Colleague

Post all of your code, please. If you're not at the point where you can solve that particular error, I'd much rather just show you the correct fix in your actual code than play twenty questions to figure out what you're doing wrong.

Narue 5,707 Bad Cop Team Colleague

The usual solution is:

cin.ignore(N, '\n');
cin.get();

Where N is a suitably large number for clearing extraneous characters from the stream.

Narue 5,707 Bad Cop Team Colleague

Formatted input (with the >> operator) and unformatted input (getline is an example) don't play well together. It's a subtle combination of features that work together to give you this bug:

  • Requests only block (wait for you to type) if the stream is empty
  • Operator >> first discards leading whitespace
  • Operator >> stops reading when it sees whitespace and doesn't discard it
  • getline() does not discard leading whitespace
  • getline() stops reading when it sees '\n' and does discard it
  • '\n' counts as whitespace, so operator >> stops on it

So what happens is you type the GPA (say 123.45) and hit enter to send input from the command line to cin. cin now contains the string "123.45\n" because the enter key is recognized as the '\n' character.

Operator >> successfully extracts 123.45 and places it in Gpa, but stops when it sees '\n' and leaves that '\n' in the stream for subsequent input requests.

Now getline() is called and sees '\n'. It doesn't block for input because there's already something in the stream, and that something causes getline() to terminate immediately and successfully with an empty string being stored in Name.

That's the "why" of your problem. Now how do you fix it? The best way is not to mix formatted and unformatted input, but if you're new to C++ that might be too much to ask. A simple solution is removing the newline prior to calling getline (an operation we often call flushing …

Muhammad Anas commented: thankyou very much for such a detailed and easy to understand explaination of a little bit ricky thing ... +1
vik.goel commented: this is so great! thanks +0
Narue 5,707 Bad Cop Team Colleague

There's no sorting going on in your code. Any ordering is coming from the files themselves.

Narue 5,707 Bad Cop Team Colleague

>else DIR * mydir = opendir(dir);
Note the else without braces. This means you have an else clause with one statement that defines a variable and then immediately destroys it. It's as if you had braces like so:

else
{
    DIR * mydir = opendir(dir);
}

mydir doesn't exist outside of implied block. Your other error is because std::string doesn't have an implicit conversion to const char* . The call to opendir() should be more like opendir(dir.c_str()) .

Narue 5,707 Bad Cop Team Colleague

There's a link at the bottom of every page (under the About Us, Contact Us, etc.. links) that will take you back to the forum index.

Narue 5,707 Bad Cop Team Colleague

New posts have been split into a new thread. usedtoworkhere, please don't resurrect an existing thread unless you have relevant information which adds to the discussion. "Me too" posts are better served with a new thread to avoid confusion in the case of similar but unrelated issues.

I'll also ask that you at least try to be respectful to the people who are kindly volunteering their free time in replying to your questions. If it gets out of hand, you could easily be in violation of Daniweb's rules.

Finally, since your problem solved itself, I'll also mark this thread as solved.

Narue 5,707 Bad Cop Team Colleague

&& has higher precedence than ||, so the evaluation looks like this:

if ( (initialize == "off" && Iminor > 20) || Imedium > 10 || Isevere > 5 || Ifatal > 0 )

When what you really want is this:

if ( initialize == "off" && (Iminor > 20 || Imedium > 10 || Isevere > 5 || Ifatal > 0) )
Narue 5,707 Bad Cop Team Colleague

Just take away the boost namespace qualification:

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

using namespace std;

template <typename Target, typename Source>
Target lexical_cast(Source arg)
{
    std::stringstream interpreter;
    Target result;
 
    if (!(interpreter << arg && interpreter >> result))
        throw std::bad_cast();
 
    return result;
}

int main()
{
    string string1 = "1";
    string string2 = "2";
    string string3 = lexical_cast<string>(
        lexical_cast<int>(string1) + 
        lexical_cast<int>(string2));

    cout << string1 << " + " << string2 << " = " << string3 << '\n';
}
lexusdominus commented: very informative and useful +3
Narue 5,707 Bad Cop Team Colleague
Narue 5,707 Bad Cop Team Colleague

There has to be some conversion. The two operands need to be converted to an integer type, and then the result of addition needs to be converted to a string. For example using boost::lexical_cast for brevity:

string string3 = boost::lexical_cast<string>(
    boost::lexical_cast<int>(string1) + 
    boost::lexical_cast<int>(string2));

boost::lexical_cast is basically just a wrapper around string streams. You can simulate it quite easily if installing the Boost library is prohibitive for some reason:

#include <sstream>
#include <typeinfo>

template <typename Target, typename Source>
Target lexical_cast(Source arg)
{
    std::stringstream interpreter;
    Target result;
 
    if (!(interpreter << arg && interpreter >> result))
        throw std::bad_cast();
 
    return result;
}

Alternatively you could perform manual addition similar to how an arbitrary precision math library might work, but that's probably excessive.

Narue 5,707 Bad Cop Team Colleague

>if(letter_counter == '\n') //|39|error: ISO C++ forbids comparison between pointer and integer| letter_counter is an array of char, but '\n' is a single char. When arrays are used in value context they're converted to a pointer to the first element, so your comparison types are char* and char , which are incompatible.

It looks like you really wanted char letter_counter[2]; to be char letter_counter; , because your usage of letter_counter doesn't suggest an array in the slightest.

>|2|error: fstream.h: No such file or directory|
fstream.h is not valid ISO C++. Your teacher is probably using a pre-standard compiler, which means you have little choice but to also use that compiler. Otherwise your valid code will fail to compile on your teacher's compiler.

I've downloaded <fstream.h> and <_def.h> and reinstalled Code::Blocks twice now...

Having the headers is pointless if you don't also have the underlying libraries.

Narue 5,707 Bad Cop Team Colleague

The function returns too. What happens after that?

Narue 5,707 Bad Cop Team Colleague

Each time the function calls itself, it calls itself with a slice of the array. The first element is sliced off, which means b[1] becomes b[0] for the next call. Repeating that process while decrementing size until size is 0 produces the recursive equivalent of a reverse traversal loop:

for (int i = size - 1; i >= 0; i--)
    printf("%d  ",b[0]);
Narue 5,707 Bad Cop Team Colleague

Can you be more specific about what confuses you?

Narue 5,707 Bad Cop Team Colleague

Look at your "overloaded" constructor. Does it allocate memory? Does it dereference the pointer as if memory were allocated?

predator78 commented: excellent +3
Narue 5,707 Bad Cop Team Colleague

Some more code would be helpful, like the relevant part of your main(). The only errors I see as far as class setup goes are that your constructor and destructor have return types, which isn't allowed.

Narue 5,707 Bad Cop Team Colleague

Unless there's a library for you to link with, adding the .cpp file to your project should be sufficient.

Narue 5,707 Bad Cop Team Colleague

Clearly you don't understand the difference between a declaration and a definition. What you added was a declaration, but what's missing is a definition. Have you written a body for that overload of Log anywhere?

Narue 5,707 Bad Cop Team Colleague

The overload of m_pParent->Log() you're calling isn't defined anywhere that the compiler can see. To start, make sure it has a definition for the type and number of arguments you're passing.

Narue 5,707 Bad Cop Team Colleague

Anything preceded by a backslash is treated as an escape character. If that character isn't one of the ones the compiler recognizes, that's a Bad Thing(TM). In your case you have '\ ', which isn't recognized. If you want a backslash in the string literal, double it up: '\\'.

Narue 5,707 Bad Cop Team Colleague
string cmd("mkdir \"/Users/" + user + "/Library/Application Support\"");

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

I'm going by your comment rather than the vague "it's failing out":

>perc = (votes / sum) * 100;
So votes and sum are both integers. Keeping in mind that any precision will be truncated, you probably wanted this instead:

perc[i] = (votes[i] / (double)sum) * 100;

By converting either operand of the division to a floating-point type, you preserve the precision long enough for the multiplication to produce a non-zero result.

Narue 5,707 Bad Cop Team Colleague

when I updated to Xcode 4 I have problems

You and everyone else. Did you hear that Apple's bug reporting server crashed after they released Xcode 4 due to the load?

Narue 5,707 Bad Cop Team Colleague

all i could find, peaople saying: it depends on the os, compiler, etc

When you rely on compiler-specific features, that's the correct answer.

For textcolor(), the portable replacement (for Windows platforms) is SetConsoleTextAttribute(). For delay() and sleep() the portable replacement (also for Windows) is Sleep().

Please write a proper answer, so anyone with the same problem can find it here.

Apparently your days of searching for an answer didn't include the search feature on Daniweb. Your question has been asked and satisfactorily answered countless times.

Narue 5,707 Bad Cop Team Colleague

Huh? I thought endianness is HW-dependent, not OS-dependent.

That's true at the OS vs. CPU level, but it's more of a practicality than a requirement. While the processor runs in a specific endian mode (some can even switch between modes), endianness at any higher level is really about performance and portability. Windows, for example, could run in big-endian mode on an x86 processor, but that would require OS level re-ording of bytes since the x86 family is strictly little-endian. For performance reasons, failing to match the endianness of the hardware is stupid.

At a higher level, file formats vary between little-endian (eg. BMP), big-endian (eg. JPEG), and variable-endian (eg. TIFF), all on the same hardware and OS. As long as programs properly process those formats in the correct order, the endianness of the OS and underlying hardware is irrelevant.

Narue 5,707 Bad Cop Team Colleague

Probably because you meant to initialize it:

bool failas = tikrinimas("example.txt");
Narue 5,707 Bad Cop Team Colleague

You neglected to mention the problems.

Narue 5,707 Bad Cop Team Colleague

So the stdafx.h file could, in theory, be empty?

In theory, sure.

With no system include files and it will compile fine?

Only if you explicitly include headers for the libraries you use. If stdafx.h is empty (in theory), then it does jack diddly as far as aiding compilation. It would be a glorified no-op.

Narue 5,707 Bad Cop Team Colleague

But why does stdafx.h have to be included at all?

When precompiled headers are enabled, you need stdafx.h. It's a Visual C++ thing. I don't even waste my time with the console project, it's easier to start with an empty project and set it up the way I want.

Why is it only present in console project?

That's not the only place it's present, but the console project does use precompiled headers by default.

Narue 5,707 Bad Cop Team Colleague

Changing the order a bit seems to do the trick. Works now.

It works for the same reason that prototypes work the way they do. If you have a using directive, it applies to everything below the directive, but not above it. Here's an example that takes advantage of this behavior:

#include <ctime>
#include <limits>
#include <random>

namespace jsw {
    template <typename IntT = unsigned, typename EngineT = std::mt19937>
    class mtrand {
        EngineT _engine;
        std::uniform_int_distribution<IntT> _gen;
    public:
        mtrand(const IntT& lbound = std::numeric_limits<IntT>::min(), 
               const IntT& ubound = std::numeric_limits<IntT>::max())
            : _engine((IntT)std::time(nullptr)), _gen(lbound, ubound)
        {}

        IntT operator()() { return _gen(_engine); }
    };
}

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

int main()
{
    jsw::mtrand<int> rgen(0, 99);
    
    // Use a lambda instead of rgen directly to avoid copying
    generate_n(ostream_iterator<int>(cout, "\n"), 10, [&] { return rgen(); });
}

Two things of note are that the headers are mixed with code, and that the using directive is prior to main, but after the definition of mtrand. This means that mtrand cannot use any names in <algorithm>, <iostream>, or <iterator>, and must explicitly qualify for namespace std. The idea is that the above is easier to work on during initial library development, but by adding inclusion guards, the first part can be split into a header without any headache at all:

#ifndef JSW_MTRAND_H
#define JSW_MTRAND_H

#include <ctime>
#include <limits>
#include <random>

namespace jsw {
    template <typename IntT = unsigned, typename EngineT = std::mt19937>
    class mtrand {
        EngineT _engine;
        std::uniform_int_distribution<IntT> _gen;
    public:
        mtrand(const IntT& …
VernonDozier commented: Good example. +15
Narue 5,707 Bad Cop Team Colleague

Which CString? Sadly, there's more than one library with a class called CString, and they all work slightly differently.

Narue 5,707 Bad Cop Team Colleague

The section Below is what i Have so far but im almost 100% certain I'm overlooking something important

What exactly is the point of your wheels function? Aside from returning a default constructed object of Wheel in all cases, you don't use the Wheel class at all. Essentially all you're doing is printing the p argument four times in an excessively inefficient manner.

On a side note, I think now is the time to bring up the rule of three. The rule of three at its simplest states that if you have to define one of the following for managing resources, you should provide all of them:

  • Copy constructor
  • Copy assignment operator
  • Destructor

In your Wheel class you need a destructor to release the dynamic memory, so both a copy constructor and a copy assignment operator are highly recommended to avoid memory leaks and shared pointer state during those operations. It might look something like this:

#include <algorithm>

class Wheel {
    friend void swap(Wheel& lhs, Wheel& rhs);
public:
    Wheel();
    Wheel(int size, int pressure);
    Wheel(const Wheel& rhs);
    ~Wheel();

    Wheel& operator=(Wheel rhs);

    void pump(int amount);
private:
    int *ptrSize;
    int pressure;
};

void swap(Wheel& lhs, Wheel& rhs)
{
    std::swap(lhs.pressure, rhs.pressure);
    std::swap(lhs.ptrSize, rhs.ptrSize);
}

Wheel::Wheel()
    : pressure(32), ptrSize(new int(30))
{}

Wheel::Wheel(int size, int pressure)
    : pressure(pressure), ptrSize(new int(size))
{}

Wheel::Wheel(const Wheel& rhs)
    : pressure(rhs.pressure), ptrSize(new int(*rhs.ptrSize))
{}

Wheel::~Wheel()
{
    delete ptrSize;
}

Wheel& Wheel::operator=(Wheel rhs)
{
    swap(*this, rhs);
    return *this;
}

void Wheel::pump(int amount)
{
    pressure += amount;
}
Narue 5,707 Bad Cop Team Colleague

Default function template arguments have been added to C++0x, yes.

Narue 5,707 Bad Cop Team Colleague

Graphs are typically implemented with an adjacency list or adjacency matrix (google it). If you're feeling especially frisky you can create the graph directly using linked nodes, but that's not necessarily recommended except as an exercise.

Narue 5,707 Bad Cop Team Colleague

Presumably you mean using Obj2 in the typedef despite it not being declared yet. You can forward declare the class to remove syntax errors:

class Obj2;
typedef Obj2*(*Reaction)();
Narue 5,707 Bad Cop Team Colleague

An unverified user is one who hasn't yet confirmed their registration from the automated email. Since you likely don't have that email from 2007, I'll see about getting that resent to you.

Narue 5,707 Bad Cop Team Colleague

Then walk through your code in a debugger and figure out why it's not doing what you want.

Narue 5,707 Bad Cop Team Colleague

cin>>option leaves a newline character in the stream. gets terminates successfully on that character immediately without blocking for input. The simplest solution is to add an ignore just after cin:

std::cin>> option;
std::cin.ignore();
Narue 5,707 Bad Cop Team Colleague

Let's analyze the error. We know that the error is coming from pentathlete_team::operator+, and that there's an issue in calling the results() member function (which is inherited from pentathlete, though that's irrelevant to the issue).

>passing 'const pentathlete_team' as 'this' argument discards qualifiers
It's pretty obvious that results() doesn't take any parameters, so the only possible way this could be involved is as the object for which you're calling results(). In other words, the sec_comp in sec_comp . results ( ) ; .

sec_comp is passed as a reference to const, so let's take a look at the definition of results and see if it can handle a const object:

void results ( ) {
    sum_res = 0 ;
    for ( int i = 0; i < 5; i ++ ) {
        sum_res += comp_res [ i ] ;
    }
}

Results is not declared as const, and it modifies the non-mutable sum_res data member, so it can't be called on a const object without removing the const qualifier. Clearly the issue is not in results(), but in operator+ not using results() as it was designed. You can remove the constness of sec_comp (not recommended):

pentathlete_team operator + ( pentathlete_team & sec_comp ) {
    if ( sum_res < 0 ) {
        results ( ) ;
    }
    sec_comp . results ( ) ;
    return pentathlete_team ( 0, 0, 0, 0 ,0, 
        sum_res + sec_comp . sum_res ) ;
}

But the problem here is that sec_comp …

Narue 5,707 Bad Cop Team Colleague

At a glance, the following raises a red flag:

else
    //countc++; // do nothing
i++;

Since you've commented out the body of the else statement, the i++; statement becomes the body. So you only increment i when all of the other cases fail. That pretty much guarantees an infinite loop.

Narue 5,707 Bad Cop Team Colleague

Semantic analysis is minimal at the lexing stage. You don't need to recognize function signatures, only the tokens that make it up. Off the top of my head, I can only think of one place in the lexical analyzer for C where context is potentially important, and that's in header name strings for an include directive. The rules for string contents are different, so knowing that it's a header name provides enough context to apply the different rules.