raptr_dflo 48 Posting Pro

vector is a template array, you can insert a element into any where you want;
like this

vector<string>vData;
vData[5] = "adfa";

Techincally, that's "replacing an element." Inserting implies moving other values out of the way. Specifically in an array or std::vector<> situation, that involves moving each element, from the desired insertion-point to the end of the array, one position farther along the array -- usually starting with the last element in the array and working backwards so you don't inadvertently overwrite any of the others. This is why the previous responder recommended using a different container class. Even a std::list<> would be an improvement for arbitrary insertion.

Of course, if the OP just wants to stick strings in a container, and relative position within the container isn't important, then a vector is a reasonable choice, and the append() method should work fine. The choice of a container depends perhaps most on what you want to do with the data -after- you input it.

raptr_dflo 48 Posting Pro

I would add that there's no point implementing operator+() until you're sure you can correctly input and output polynomials. I suspect something's going to need to change in how you define your Poly class.... (Hint: in your non-default constructor, how big is the array coeff[]?)

raptr_dflo 48 Posting Pro

I'm sorry, I completely misunderstood your original post. If I now understand correctly, you're requesting help implementing recursive functions that perform certain tasks on linked lists. Specifically one that splits list L into two equal-length lists P and Q.

There are a variety of ways to go about this. You could use counting to:
1) determine which of P or Q is currently shorter (and thus should be added to next)
2) determine whether the length of L is even or odd (so you know which new list to add to next)
3) try to figure out where to split L so that P can point to the first half and Q can point to the second half (but this isn't recursive, only your count() function is)
4) and probably others!

But, given idea #2 above, can you think of a way to do the same thing (alternating between P and Q) without counting the number of elements in L?

raptr_dflo 48 Posting Pro

I did my serial-port programming in a Unix environment, so the low-level structures are probably different in Windows, but the bottom line was I could open the serial port like a file and use the low-level file operations to read/write, like:

int fd = open("/dev/ttyS1", O_RDWR);
/* do some serial-port-specific control/initialization stuff */
...
if (write(*dataptr, word_size, num_words, fd) != num_words) {
    /* error writing to port */
}

Looks like the .NET Framework for Windows provides a SerialPort class which will presumably help to encapsulate some of the mess.

raptr_dflo 48 Posting Pro

Looks right to me:

SomeType someVariableName[constHowManyToAllocate];
int int_array[10];
char text[256];
const int HASH_SIZE = 250;
std::list<int> hash_array[HASH_SIZE];  // OK: HASH_SIZE is known at compile-time

Does it compile? Does your code appear to be running correctly?

raptr_dflo 48 Posting Pro

Following Moschops input, the "where" command in GDB also shows you (briefly) the current function-call stack, which I've found useful if for no other reason than to get a quick idea of how many "up" commands I need to enter before I get back to my own code, and occasionally "Oops! How did i get into this function from THERE???"

If you can master where, up, down, and print you're in great shape. Then move on to "stop at", "stop in", "continue" and "step" (I believe, read the info or man page to get all the details straight...)

raptr_dflo 48 Posting Pro

Oh, and a lesson learned from my own college experience: doing the assigned reading and attending lectures makes it MUCH easier to understand the material and thus to complete assignments and pass exams. Good luck!

raptr_dflo 48 Posting Pro

I don't know what you're supposed to do, I'm not in your class. If the assignment isn't clear, ask one of your classmates, the professor, or a teaching assistant if your course has one.

As for what "ADT" stands for, I hadn't seen the acronym before either, but learn something from this: http://lmgtfy.com/?q=Iterator+ADT ... the second result looks promising.

raptr_dflo 48 Posting Pro

I'll ask you questions in return. See if they help.

For the first example, what values are provided by the user? How are they then used in the code? What -could- the user provide? What if he/she inputs something unexpected?

For the second example, do you understand what is meant by "side-effect"? What is the function called? What does it return? What else does it do?

raptr_dflo 48 Posting Pro

In response to your question:
ptr is a pointer, but ptr is not, it's been declared to be an int. Even if ptr were a pointer, std::list<int> is not a pointer, its an instance of a class which internally manages a pointer (or several, the point is, you shouldn't need to know how it's implemented in order to use it). std::list<int>.begin() is a pointer to a std::list<int>::iterator object, so now you might be getting close, but any halfway decent compiler is going to issue a warning that a "int *" isn't the same as a "std::list<int>::iterator *", though it will probably still compile at that point.

raptr_dflo 48 Posting Pro

If you want a dynamic array of std::list<> containers, then declare ptr correctly in your class definition:

std::list<int> *ptr;

and allocate it correctly in your constructor:

ptr = new std::list<int> [size];

Then I think the rest of your code will work as intended. (And don't forget to pass the HashTable size in as an integer, not a const Entry &!)

If you mean to use the code as I posted it, yes you would need to allocate the lists somewhere, but until you know how much memory you need, there's no point doing it in the constructor.

The advantage of the STL containers is that they hide all the ugly details of the memory management from you. The disadvantage is that you then don't learn how dynamic memory works. At least, not the way you learn it if you have to implement it yourself, and get it right! :)

Here's a class I've re-written enough times ... I'm doing it from memory, so bear with me if there are compiler errors! It should give you an idea of what's really involved in allocating memory dynamically, and keeping track of where you're at. Now you know why there's a Standard Template Library, especially of already-implemented containers! :)

class GrowableIntBuffer
{
private:
    int currentSize;
    int maxSize;
    int *data;

    void growBuffer();  // called as needed by appendVal()

public:
    GrowableIntBuffer();
    ~GrowableIntBuffer();

    void appendVal(int val);
    void print();
};

GrowableIntBuffer::GrowableIntBuffer() :
    maxSize(0), currentSize(0), data(NULL)
{
    // members will become more …
raptr_dflo 48 Posting Pro

Close. (And in the future, please use [ CODE ] tags around your code -- select a code segment and click the button/icon at the top of the editor.)

In part 3, remember which class you're providing the implementation for. Then, how are the studentName and studentScore going to get initialized in the constructor (hint: you should be re-using the existing constructor as appropriate).

Also, if you want to know if your code is correct, add a

int main ()
{
   ...
   return 0;
}

block somewhere, have it create a couple of instances of your class, and print the values returned from the observer-methods. If the code compiles and your tests print out the same values that you passed to the constructors, then your code is minimally correct. If it won't compile, the compiler error messages tell you exactly what you did wrong, and often enough where in the code the mistake is (other times, only where the compiler couldn't figure out what to do next, and the actual error might be a ways back). If it doesn't print the correct values, you need to go back and see why not.

raptr_dflo 48 Posting Pro

It looks pretty good the way it is. What problems are you having with it?

raptr_dflo 48 Posting Pro

Happy to help!

raptr_dflo 48 Posting Pro

Also, why are the expressions in your for() loops different between the two Sort() functions? I would think you'd want to iterate over the items in the array the same way, just changing what field you're comparing....

raptr_dflo 48 Posting Pro

Hmmmm, a couple of things. First of all, if your HashTable constructor is supposed to take the size of the table (and just store items of type Entry), then you should probably specify its argument as type int instead of const Entry & . Assigning the parameter to an integer at line 27 only works for certain types, and Entry could be almost anything.

Then, you can't assign a std::list<int> to an element of an array-of-integers. If you can use STL containers anyway, you could just have a vector<> of lists, and I think your constructor can be as simple as:

template <class Entry>
HashTable<Entry>::HashTable(int size)
{
    // std::vector<std::list<int>> table;
    table = std::vector<std::list<int>>(size);
}

where std::vector<type>(val) creates a new vector of initial-length val , storing elements of type type .

If you're required to use arrays instead, then something more ugly like the following would work:

template <class Entry>
HashTable<Entry>::HashTable(int size)
{
    // int **table
    table = new int* [size];
    // new" probably default-initializes the int* array members to NULL, but if not:
    // for (int i = 0; i < size; i++)
    //     table[i] = NULL;
}

... keeping in mind that before you can use one of the "lists" in table, you need to allocate an appropriate amount of memory and assign that back to the table-entry.

raptr_dflo 48 Posting Pro

Probably because of when you check for errors on your input stream:

do
{
    fil1.read((char*)&e,sizeof(e));
    e.display1();
 
    fil1.read((char*)&s,sizeof(s));
    s.display2();
} while (fil1);

After you've read the last e and s out of the file, the fil1 stream is still in a valid state, so you repeat your loop one more time. Each read fails, but since there's no data to replace the variable, it maintains the same values it had from the previous read, so prints the same line as previously.

One solution is to test the state of fil1 after reading e (but before printing it), and if it's at EOF or otherwise in an error-state, break; out of the loop at that point.

raptr_dflo 48 Posting Pro

Um, no. Your constructor -is- a method, albeit a special purpose one, but the same rules hold true. If you declare a new variable within the body of the constructor, then it exists only within that scope (until the constructor returns).

The alternative is as I coded it: declare the array as a member of your class, and -initialize- it in the constructor. Unless, for whatever reason, the array is needed only during the execution of the constructor, and no other method of the class needs to access it. Then you can declare it in the constructor, but still need to do so dynamically:

int array_size=0, *array_test=NULL;
if (size > 0) {
    array_test = new int [size];
    if (array_test)
        array_size = size;
}
...
raptr_dflo 48 Posting Pro

its perfectly fine to delete a null pointer

Lucky me! This is what I get for starting with C programming, and then learning C++ later ... I'm way too careful about handling pointers! And yes, I'm old enough to pre-date a usable C++ compiler.

raptr_dflo 48 Posting Pro

I'll take a stab at understanding you:
You find the fundamental object-oriented concepts difficult to understand, particularly inheritance (how a derived class automatically inherits members and methods from its parent class, and only new or changed functionality needs to be specified) and exceptions (a way of propagating error conditions back to the first caller in the chain with code that "catches" that exception, outside the normal function call stack). Am I close?

As far as gaining a better understanding of these concepts, if you can understand what I wrote above, then the next step is to clearly formulate a question regarding more specifically exactly what part of the concepts continue to cause you confusion.

All smart-assery aside, we really are here to help, but we're not going to teach you a course in "essential object-oriented concepts" for free.

raptr_dflo 48 Posting Pro

Isn't a vector a dynamic array?

Yes and no. A std::vector is a templated container-class which acts similarly to a C-style array, and will dynamically increase the amount of memory it needs without your direct intervention.

The other responder probably meant using a pointer and dynamically-allocated memory to be used as a C-style array, and either way do youreally want the array declared locally within your constructor?

template <class Key>
class HashTable
{
private:
    int array_size;
    int *array_vals;

public:
    HashTable(int array_size); //constructor
...
};

template <class Key>
HashTable<Key>::HashTable(int req_array_size) :
    array_size(0), array_vals(NULL)
{
    if (req_array_size > 0) {
        array_vals = new int [req_array_size];
        if (array_vals)
            array_size = req_array_size;
    }
    ...
}
raptr_dflo 48 Posting Pro

Your code adds the 32-bit value to each 32-bit word of your instance. I doubt that's what you intended. Instead, if the returned carry is non-zero, you need to add that to the next 32-bit word of your instance, and repeat (in case that carry-addition overflows) until you get a zero-carry back.

This means I can just return a 1280bit(640*2) class, when multiplying with two 640bit classes plus an overflow occurs?

That's one approach. Or, you can make your existing class more generic by including its length and allocating the amount of space you need:

class Unfinitebits
{
private:
    int numBits;
    int numWords;
    unsigned long int *m_data;

public:
    Unfinitebits(int howBig) :
        numBits(0), numWords(0), m_DATA(NULL)
    {
        int words = (howBig + 31 / 32);
        m_DATA = new unsigned long int [ words ];
        if (m_DATA) {
            numBits = howBig;
            numWords = words;
        }
    }

    ...
};

Then you can either have numBits tell you the maximum bit-length of the value you can store, or have it tell your the actual bit-length of the value currently stored (rather than searching for the highest set-bit). Or include a maxBits member so you can have both.

Then if you know the actual bit-length of two 640-bit values, you can immediately determine the bit-length of the product and allocate a new Unfinitebits instance of the correct length.

Keep in mind that if you subtract two values, you may need to recompute numBits from scratch. Or else ensure that any approximation is …

raptr_dflo 48 Posting Pro

Since I don't see anything obvious wrong with your function itself, how are you allocating the Request* that you're passing into the function?

raptr_dflo 48 Posting Pro

Welcome ThePolid,

Unfortunately it's hard to tell what might be wrong with your program, since we don't know what your intention is. What is your program supposed to do? There's an appalling lack of documentation and intelligently-named variables. Please don't make us do this much work just to get started!

That said, your while() loop at line 11 does nothing. In fact, if num starts out >= 0.75, it will get stuck there forever. Try:

while (num >= 0.75)
{
    ...
}

Also, the modulo-operator ("%") gives "the remainder when dividing a by b". I'm not sure that's meaningful for floating-point numbers, and regardless, testing floating-point results for exact equality is dangerous, since many values which seem obvious enough (like 0.1, for instance) can't be exactly represented in binary, and computations tend to introduce tiny amounts of unexpected error.

Since the arbitrary numeric constants appear to reflect denominations of U.S. currency, I'd instead recommend converting the floating-point input to an integer number of cents: int cents = int(num * 100 + 0.5); (The addition of 0.5 provides rounding correction so that 0.99999997 gets converted to 100 cents, not 99 cents).

Then work with integers to do what you need.

raptr_dflo 48 Posting Pro

Did you make your implementation match the method-declaration in the class? We don't need 1,000 lines of code, the original error message told you exactly what the problem was: you originally declared your insert() method to take type Entry & which allows the argument to be altered within the method, replacing the original passed-in value; you can't pass a numeric constant to that, since it can't be altered. You must either declare an int variable, and pass the variable (whose value -can- be altered), or (since your implementation isn't changing the value being passed) declare the argument as const Entry & , meaning you're still passing by reference but guaranteeing that the value won't be changed, so that passing a constant is OK.

If doing the latter, just make sure you change the insert() method specification in both places (in the class definition at line 17, and the method implementation at line 55, in HashTable.h). And because insert() then calls hash_function() with the same parameter (which, if you passed a numeric constant, still can't be altered), you need to do the same for that method.

raptr_dflo 48 Posting Pro

You don't need NTFS-specific library, there are higher-level FS-agnostic APIs to get the minimal information you need. I did a quick search for "recurse through directory" on http://msdn.microsoft.com/ and found this discussion, which includes enough source-code to get you started.

raptr_dflo 48 Posting Pro

I can't tell you why fil1.write() and fil1.read() aren't working, without more information. What values are you entering for e1? What file gets generated when you write() it? What is in e1 after you read() it back?

I don't know what your professor meant by "write it via object." To me that means something more like:

class emp
{
...
    void write(ofstream & fil) const {
        fil << name << " " << num << " " << dep << " " age << endl;
    }
    void read(ifstream & fil) {
        fil >> name >> num >> dep >> age;
    }
...
};

so that later you can do:

e1.write(fil1);
    e2.read(fil2);

There's nothing wrong with your logic, if it addresses your assignment. However, what you specified is

question:-
Write a C++ program to merge the content of two files namely “Employee.txt”
and “Salary.txt” into “EmployeeDetails.txt”.

and what you've programmed does not do that, it generates all three files at the same time. I'm just trying to help.

As far as writing out binary files (using read() and write() the way you are so far), I think you need to open the files in "binary" mode. Include flag ios::binary when you open the file. And if the only operation you're performing on a file is writing (or reading), then don't specify the other flag, just ios::out (or ios::in), not both.

raptr_dflo 48 Posting Pro

I've been doing "desktop application" programming almost forever, it feels like. For the past couple years, using the Qt framework (http://qt.nokia.com/, not Apple's QuickTime library). It may be a bit hard to come up to speed on initially, but it nicely handles more complex aspects of GUI design, including managing multiple windows and inserting images. It incorporates substantial drawing support, and even CSS notation for GUI element styling. Plus a robust communications paradigm between objects, called "signals and slots", rather than the more traditional C-like "register a callback function" paradigm.

I've specifically been programming in Python and the PyQt bindings from Riverfront Computing, but it's very close to the C++ API, and I've dug through various parts of the Qt C++ source code as well.

As far as IDE, Visual Studio is pretty much the accepted gold standard on Windows. You can download and use Visual Studio Express for free, and purchase the Professional version later, if you find you need the additional functionality.

raptr_dflo 48 Posting Pro

You have an extra close-curly-brace '}' at line 101. Cheers!

raptr_dflo 48 Posting Pro

Regardless of which compiler you're using, how are you declaring your class, and how do you expect to use it? Anything you wish to access from outside the class implementation should be declared public: ... by default, the contents of a C++ class are private: . There's also a protected: declaration that allows access from derived subclasses.

class MyClass
{
private:  // this is already the case
    int intVal;
    std::string strVal;

public:  // these are the parts you want outside access to
    MyClass();
    MyClass(int anIntVal, const std::string &aStrVal);
    MyClass(const MyClass &other);
    ~MyClass();

    void setIntVal(int anIntVal);
    int getIntVal() const;

    ...

private:
    // more private stuff

...
};

The point of "friend" is so that a class can tell other classes that they have access to non-public members, purely as a convenience. If you could do that from outside a class, then you defeat the reason to have any privacy at all (and the reason is to enforce OO notions of encapsulation/abstraction).

raptr_dflo 48 Posting Pro

Oh, and the sort involving swapping successive neighbors is "bubble sort", not "insertion sort" ... if you need to implement insertion sort, then the procedure is different: take an item out of a scrambled list, and add it into the correct place in a new list, moving items out of the way as needed. You can do this in-place using a single array by keeping track of how many items K you've inserted. The first K items should be in sorted order, and the remaining N-K items are the scrambled items remaining to sort.

Either way, hand-sorting N real-world objects (where N is big enough to eliminate trivial answers, and small enough that you can finish in a reasonable amount of time) will really drive home the logic involved.

raptr_dflo 48 Posting Pro

A couple ideas:
1) Your swapping code in lines 6-9 is broken. Watch the order of those lines.
2) If your swapping was correct, your inner loop would execute either once or not at all, so it should just be an if() statement
3) Once you've found two values to swap, you can't just blindly go on as if nothing happened -- instead of blindly hacking at it, do this with a real physical deck of playing cards (one suit is enough): shuffle them up, lay them out in a row, and start swapping neighboring cards as needed. Start at one end of the row and see what you need to do each time you find a pair to swap, until your row is sorted into order. Now write that logical process into code.

raptr_dflo 48 Posting Pro

Why do you expect:

fil1.write((char*)&e1,sizeof(e1));

to write a human-readable line like your sample indicates? That's one (non-portable) way to write a terse binary record. Instead, for text files, keep it simple:

fil1 << e.name << " " << e.num << " " << e.dep << " " << e.age << endl;

and reverse that to read it back in:

fil1 >> e.name >> e.num >> e.dep >> e.age;

(Note, whitespace (including endl) tells the istream::operator>>() where to find boundaries of "items" and isn't read into any item. Use getline(fil1, lineString) to read an entire line (including whitespace) into a std::string variable.)

Also, if you need to create the files as well as merge them, then make those operations separate. Open a file for writing, fill it, and close it. Open another file for writing, fill it, and close it. Then open both files for reading, and a new file for writing, and perform the merge.

raptr_dflo 48 Posting Pro

Let's start at the beginning.

1.) At line 14, you declare a two-dimensional array of int-pointers using uninitialized values of row and col, so who knows how big your matrix actually is.

2.) You then input a value for row, and assign col to be the same value, in lines 16 and 19.

3.) Finally you attempt to print out a bewildering set of junk characters, presumably looking something like:

|---|---|---|---|
|---|---|---|---|
...

... except you loop j over "row" instead of "col" (even though they're the same in this case, it's still silly); i can't tell why you loop k over [0,count] where count is also zero, is this so you can print more than one separator between successive vals in a row?; and you never reference your array of int-pointers at all. Of course that last point isn't an issue, since you also never fill your array with any values. And if you want it to store integers, it should be declared as int array[row][col]; (note, I removed the "*").

Also, note that Narue added [ CODE ] tags for you. Please do this yourself in the future. Use the "[ CODE ]" icon-button at the top of the editor. You have three options:
1) click the button first, then paste your code in between the start-tag and end-tag
2) paste your code first, then select it all and click the button
3) hand-type the tags yourself
whichever best …

raptr_dflo 48 Posting Pro

Please mark your thread as "solved" when you're finished with it. Thanks!

raptr_dflo 48 Posting Pro

So which functions do you need to write? They all look "written" to me....

Accessing the system clock may be dependent on what operating system you're running on (Windows, Linux, other), and what APIs you have available. If you're running in Windows, try searching http://msdn.microsoft.com/ . It's often hard to filter out the results that -aren't- relevant, but eventually you should be able to find what you're looking for.

For future reference, we really don't need to see your entire working source code for this kind of question. Something as simple as the following would suffice, assuming I've understood your question:

void doSomething()
{
    cout << "blah!" << endl;
}

int main(int argc, char *argv[])
{
    clock_t startTime = clock();
    for (int i=0;  i < 1000000;  i++)
        doSomething();
    clock_t endTime = clock();
    cout << "took " << (endTime - startTime) << " ticks" << endl;
    return 0;
}

Speaking of understanding your question, please learn how to articulate your questions more clearly, such as "I need to determine the execution time of a piece of code; how would I implement the clock() function in this code sample? Is there a system function that returns relevant timing information? Perhaps a CPU instruction counter, or elapsed real or virtual run-time? I'm running Windows 7, in case that matters."

raptr_dflo 48 Posting Pro

Sounds like an interesting project. Have you written code that communicates over a serial-port before? It's been so long since I've done so (more than 10 years ago) that I wouldn't be much help. I suspect a Google search would get you well underway.

raptr_dflo 48 Posting Pro

Let's start with your data structure:
so far you have a single array of characters; I think you need at least an array of strings. In fact, to store girls' names and boys' names, you probably want two arrays of strings, one called girls_names and one called boys_names. You should at least be using the std::string class to manipulate strings in C++. Depending on where you are in your learning-process, you may also want to consider using the std::vector container instead of C-style arrays. And you may want a higher-level data structure than just two separate lists of names.

Now, looking at your fillArray() function, you have declared boy and girl as a single individual char each. Again, you want each of these to be a string (preferably a std::string, or at least an array of chars). Then, it should be obvious to you, looking at your own code, that you don't actually store either boy or girl into your array.

So start with getting your data-types right, defining useful data structures (useful to solving your problem, not just to holding the data), and getting your data structures loaded from your input file. Once you have that much working, it will be easier to see how to update your search function, and then how to tell if it is doing what it needs to.

raptr_dflo 48 Posting Pro

Don't worry about it. It might be obvious what you want it to do, but that doesn't mean it's "simple." :)

And yeah, you don't want weird "magic numbers" in your code to fix logic problems. Instead, you need to get your logic correct. Let's state your logic for the record (you may find later that there's a way to consolidate it into something more concise, but still readable/maintainable, but for now, let it be really explicit until it works):

// pseudocode
if movement is downward-only:
    if collide with top of obstacle:
        update p.y
else if movement is down-and-right:
    determine whether colliding first with top or left edge (or neither) of obstacle
    if collide with top edge of obstacle before left edge:
        update p.y
    else if collide with left edge of obstacle before top edge:
        update p.x
    else if collide with both at same time (exactly onto the corner):
        decide what to do -- pick one?
...

Now it already occurs to me, for your case, that you can set up some variables ahead of time:

if (yVel <= 0)
    collide_top = false;
else
    // need to check
...

And if your speed can be large compared to the size of things to collide with, then instead of seeing if a point has gone inside an obstacle, check whether a point -will- (or has just) crossed an edge:

// top edge
collide_top = False
if (yVel > 0 && obj.y + obj.h >= obstacle.y && obj.y …
raptr_dflo 48 Posting Pro

Among other things, you may have NULL pointers in your vector, which can't be delete d. Verify what's in your vector before you worry about what's wrong with your deletion code, e.g.:

// changed to while() loop to make logic more obvious
vector<T*>::iterator iter = x.begin();
while (iter != x.end()) {
    T* ptr = *iter;
    if (! ptr) {
        // NULL pointer in your vector
    }
    else if ( /* test to see if element should be removed */ ) {
        delete ptr;
        iter = x.erase(iter);
    }
    else
        iter++;
}
raptr_dflo 48 Posting Pro

OK, I'm going to start from the beginning. Assume I know nothing. I understand that you want to manipulate really big numbers. What values are you storing into your m_DATA array of unsigned ints? Single decimal digits [0-9]? Or arbitrary unsigned 32-bit values? Either way, your assignment to unsigned int help at line 7 (in the first code segment above) is questionable. For instance, if value is bigger than 2G (half the largest value you can store in a 32-bit unsigned val, not that it would be that big, but it -could- be, and it illustrates the problem), then any value of *iter greater than 1 will cause help to overflow.

If you know you're storing "reasonable" values in m_DATA , and passing "reasonable" values for value (and you may want to document this clearly in your code), then you should be OK, but then think about what happens when you multiply two "reasonable" values together, and make sure the result you're storing is also "reasonable", with an appropriate (iterative) carry-operation to move the rest of the result into higher-order positions.

If you're using m_DATA to store consecutive sequences of 32 bits, then you can -never- guarantee that your individual multiplication will work. Instead, note that the product of two 16-bit unsigned values will always fit into a 32-bit unsigned value. Either create your storage array to hold unsigned short int values, and promote each value to 32-bits before applying an operation (which now won't overflow), and then …

raptr_dflo 48 Posting Pro

Yes, that's certainly one way to handle it, assuming you insert that line at the correct place in your code. If it's working now, please mark your thread as "solved". Good work on this!

raptr_dflo 48 Posting Pro

I can't read minds. If you've changed your code, and it still doesn't work for you, please post your current code so we can all see what it looks like now!

raptr_dflo 48 Posting Pro

For your own sanity (and that of others reading it), please indent your code, e.g.:

void functionName (type1 arg1, ...)
{
    some statements;
    while (condition) {
        more statements;
    }
}

Also, when your problem is simply that your code isn't opening the specified file, don't post 200 extra lines of irrelevant functions. Trim the source down to what demonstrates the problem, and post just that.

That said, I don't see anything obvious wrong with your code. Is the filename printed out correctly and completely in your else-block? In particular, if there is any white-space in your path, cin >> ... is going to break at that point, instead use getline(cin, fileName); .

Also, just because the file didn't open correctly doesn't mean the file wasn't found. What are you typing in for your filename? What is the error message printing back out?

raptr_dflo 48 Posting Pro

Yeah, it looks like that's exactly what your code would have it do, so you need to be smarter. cCol() needs to determine not only "are the objects colliding at all?" but also "which edges are colliding?"

Consider returning, instead of a bool (colliding/not-colliding), a bitwise-or of edge flags:

// caution: pseudocode!
enum {NoEdges=0, TopEdge=1, BottomEdge=2, LeftEdge=4, RightEdge=8};
int cCol(obj, obstacle) {
    int obstacle_edges = NoEdges;
    if (obj top-left corner in obstacle) {
        if (obj top-right corner in obstacle)
            obstacle_edges |= BottomEdge;
        else if (obj bottom-left corner in obstacle)
            obstacle_edges |= LeftEdge;
        else
            obstacle_edges |= (BottomEdge | LeftEdge);
    }
    ...
    return obstacle_edges;
}

This is quick-and-dirty as it occurred to me, there are presumably MUCH smarter ways of determining which edge(s) of the obstacle that the object has just collided with, or even if that's the most appropriate information to return.

And given the behavior you desire, you may even wish to pass into cCol() which edges you're interested in ... i.e., when sliding down the left-edge of the obstacle, the only thing you actually want to know is when you're no longer colliding with the left-edge -- with the next update, no vertex of your object is within the obstacle.

raptr_dflo 48 Posting Pro

First of all, there's probably no need to keep checking cCol(dBox, floor) over and over. The point of handling collision detection is so that after you're done, the objects are no longer colliding.

My next question is: is it possible for xVel and yVel to be non-zero at the same time? I.e., can your object move diagonally, or only up-down-left-right? (I don't have enough of your code to determine that.) If your motion is guaranteed to be limited to the 4 cardinal directions, then your collision code can look more like:

if ( cCol( dBox, floor ) )
{
    if ( yVel > 0 )
    {
        dBox.y = floor.y - dBox.h;
    }
    else if ( yVel < 0 )
    {
        dBox.y = floor.y + floor.h;
    }

    if ( xVel > 0 )
    {
        dBox.x = floor.x - dBox.w;
    }
    else if ( xVel < 0 )
    {
        dBox.x = floor.x + floor.w;
    }
}

Note that yVel can't be simultaneously <0 and >0 (same for xVel), so "else if" is ok.

Now, it looks like you handle dBox.x and dBox.y correctly, but what do you want to have happen to xVel and yVel? Do you want dBox to bounce off the floor? If so, you need to negate one or the other (depending on how you intersected). Do you want dBox to slide along the floor object? If so, set the appropriate xVel or yVel to zero so it doesn't keep trying to go through. Do you …

raptr_dflo 48 Posting Pro

I don't know how big a manualSetPosition object is, but I wonder do you really need, what, 1.5 million of them? I was about to say I can make an image with 1920 x 1280 "pixels" with no trouble. But then I tried, and sure enough, it looks like I can allocate only a little over a million bytes on the stack, perhaps there's a 1MB default limit per process in Windows?

Anyway, it's easy enough to allocate it on the heap instead:

#include <iostream>
using namespace std;


int main (int argc, char *argv[]) 
{
	class FPixel {
		float r, g, b, a;
	public:
		FPixel(): r(0.0f), g(0.0f), b(0.0f), a(0.0f) {}
		void setRed(float v) { r=v; }
		float getRed() const { return r; }
	};

	cout << "size of FPixel " << sizeof(FPixel) << endl;

	// FPixel fImage[1080][1920];  // this causes a Stack Overflow exception: allocates statically -> from the stack
	FPixel *fImage = new FPixel [1080*1920];  // this works fine: allocates dynamically -> from the heap

	cout << "Type something: ";
	int val;
	cin >> val;

	return 0;
}
raptr_dflo 48 Posting Pro

You are correct, you have a logic error (more than one) in your while() loop from lines 25-29. How do you start the loop if you haven't yet read a score? Once you -do- read a score, what happens if it's -1?

raptr_dflo 48 Posting Pro

Instead of reading the entire line into one string, try reading the individual fields into strings (and for now assuming that your input will always have exactly three space-separated fields per line). I'm also going to assume you've covered basic structures, so that you can sort more efficiently:

struct Student {
    string firstName;
    string lastName;
    string id;
};
Student students[NUMBER_STUDENTS];

...

inStream >> students[index].firstName;
inStream >> students[index].lastName;
inStream >> students[index].id;

As far as why it always puts things in students[0]: because that's what you tell it to do. You have more loops there than you need. The outer while() loop keeps going until the input is exhausted. The inner for() loop executes only once at a time, assigning index to 0, then reading a line and assigning it to students[index==0]. Since this isn't what you intended, just say out loud exactly what you -do- intend, and modify the code so it does what you said.

raptr_dflo 48 Posting Pro

Write down the givenword "TENT" in a horizontal sequence of 4 boxes, one letter per box, to emphasize the array-ness of the string. Do the same for dictionaryword "TEE". Follow your own code, one line at a time, doing exactly what it says. What result do you get? Is it correct? If not (hint, I wouldn't be asking you to do this otherwise), what do you need to change or add to make it work correctly?