raptr_dflo 48 Posting Pro

Happy to help. Don't forget to mark the thread as "solved"! Or post back if you have more questions on the same program. :)

raptr_dflo 48 Posting Pro

Try: g++ game.cpp -o game -Wl,-static -lpdcurses or g++ game.cpp -o game -static-libgcc -Wl,-static -lpdcurses (from http://ubuntuforums.org/showthread.php?t=852552 , your mileage may vary, also this requires a libpdcurses.a file which you may have to create by hand ... by extracting the individual .o files out of a .dll and re-archiving into a .a)

raptr_dflo 48 Posting Pro

Yuck. Not that it helps, but I've seen plenty of examples where warning 4244 is explicitly silenced in the build, rather than correcting the problem. :)

Unrelated, your "load" method should probably be declared "static" as a class-method instead of an instance-method.

raptr_dflo 48 Posting Pro

I'm sure somebody will have a more definitive answer, but the basic problem with allocating small objects from the heap is the amount of overhead necessary to keep track of that object, and the extent to which the available heap memory is fragmented as small objects are allocated and freed in arbitrary order. The exact value of "small" will depend on a variety of factors including the word-size of your operating system (to store the address of a pointer, generally 32 bits or 64 bits), the amount of memory at your disposal, and how much waste you're willing to tolerate.

If you know you want to allocate consistent small objects like integers (not that a savvy developer would generally allocate an integer at a time anyway), you could always allocate a block of memory, big enough to store 100 integers, or 10,000, depending on how many you're likely to need, essentially:

int *ints = new int [100];

and then manage yourself which is which and whether you're using it or not, and knowing when you can safely free up the whole block. The problem is clearly also application-dependent. I do a fair bit of image-generation programming, so I'm always needing to store red, green and blue values (or more), each of which is usually at least an 8-bit integer (and often a float instead) for each pixel in a W-by-H-pixel image -- allocating the entire image in a single block of memory is smarter than, say, creating a …

mike_2000_17 commented: nice +14
raptr_dflo 48 Posting Pro

Ok, so what you'll start with is some value x, and you'll write a function that computes ln(1+x) by using the formula above:

double ln_one_plus_x(double x)
{
    double val;
    // insert math here
    return val;
}

Now you want to use exponents from 1 to 100 inclusive, so a loop is in order.
Each term will be added (if the exponent is odd) or subtracted (if the exponent is even) to/from the total. And instead of computing the powers-of-x for each term, you can notice that x^57 = (x^56 * x). And then the power-of-x for each term must also be divided by the power. Is that enough to get you started? If you need to test your result, try http://www.cplusplus.com/reference/clibrary/cmath/log/ (and note that the formula given is valid when |x| < 1, otherwise the powers-of-x grow instead of shrink and the formula diverges from any solution).

raptr_dflo 48 Posting Pro

Anuradha,
You said in your original post:
>> This is my code .I want to print the numbers whose only prime factors are 2, 3 or 5.

If you want to print the first 12 primes, that's a different exercise!

1 is not a prime number (by consensus, as it's also not a product of prime factors, it's just a special case). Each number greater than 1 is either a prime number or is the product of some set of prime factors, each of which is smaller than the number:
2 is prime, 3 is not divisible by 2 so 3 is prime, 4 is the product of 2 and 2, and so on. Each time you discover a prime, print it out and increment your counter, until you have printed however many you want (in your case 11).

int count = 0;
int potential = 2;
while (count < 11) {
    bool is_prime = is_num_prime(potential);  // determine if potential is prime
    if (is_prime) {
        cout << potential << " is prime" << endl;
        count++;
    }
    potential++;
}

I've left the is_num_prime() function for you to complete (if any number smaller than the number you're testing divides it evenly, then the number is not prime -- there are a number of efficiencies you can make -- think about: which numbers should you divide by? when can you stop?). Get it working first, then do a search on "sieve of eratosthenes" for an approach to …

raptr_dflo 48 Posting Pro

first google result for "outtextxy" says:

void outtextxy(int x, int y, char *textstring);

Note the "*" character, indicating that it expects a C-style string (or Null-character-terminated array of characters) for the text to display, not a single character. Replace your first line above with:

const char* strings[] = {"1", "2", "3", "4", "5"};

Note the double-quotes instead of single-quotes around each value! (and index into the array as Satyrn suggested...)

raptr_dflo 48 Posting Pro

It is also generally considered "a bad thing" to use global variables, as you have declared in lines 16-19. Instead you should pass the ones you need to each function: by reference for "output" values that the function should alter, and by copy (or const reference) for "input" values. Conversely, if you're going to make all the variable global anyway, you don't need to pass any of them into your functions.

Is there a reason you loop over your input/convertToMinutes/convertBack/output 12 times for the first customer? If you don't reset count, you won't loop at all for your next customer(s).

Your upper-limit validation for hours and minutes are incorrect in opposite directions: 25 is not a valid hour (but will pass), 59 is a valid number of minutes (but will fail). What happens if the customer enters at 23:30 Friday night, and leaves at 1:30 Saturday morning?

raptr_dflo 48 Posting Pro

You should also consider printing something besides the initial "1" if you want to see a list of numbers.

If a number's ONLY prime factors are 2, 3, and/or 5, then you should be able to divide evenly by some quantity of each of those factors, and be left with 1.

bool factorsAre2And3And5(int val)
{
    if (val < 1)
        return false;
    while (val > 1) {
        if (val % 2 == 0)
            val /= 2;
        else if (val % 3 == 0)
            val /= 3;
        else if (val % 5 == 0)
            val /= 5;
        else
            break;
    }
    return (val == 1);
}
raptr_dflo 48 Posting Pro
bool keep_running = true;
while (keep_running) {
    // do program stuff
    // prompt whether to keep running
    // handle response
}
return 0;
raptr_dflo 48 Posting Pro

Shaky Rox, you've posted into a three-year-old thread, in general if you have a question about an inactive thread, copy any relevant info into a new thread.

Meanwhile, you can insert your own "printf()" statements if you wish to echo back what the user typed.

raptr_dflo 48 Posting Pro

In fact, beyond the fundamental insertions and deletions, link surgery isn't as common in linked lists as you might think. Linked lists are generally reserved for simpler tasks where complex structure changes are unnecessary.

Good point. While a fairly common recurring "programming test" given during interviews is "write code to reverse a singly-linked list", link surgery (as you so aptly put it) tends to show up more in maintaining a heap or a sorted-and-balanced tree of heavy-weight objects. But it's easier (for me, anyway) to start thinking in just the one-dimensional linear world of a list before getting more involved. Thanks for the additional insights!

raptr_dflo 48 Posting Pro

It will help if you understand what combustion's code is doing in the first place.

A previous commenter pointed out that recursion isn't strictly necessary for this problem, and probably slows down the algorithm a great deal. In addition, his recurse() function calls checkPassword() too often: since he's looping over desired password-width outside of the function, he should only be checking the password if the postion == width-1 (he's filled the password to the desired width), the code calls the function for all widths as the recursion unwinds. Finally, another commenter also pointed out an actual error in the code: as written, an input password with a 'z' in it will never be matched.

That said, it's very hard (if not impossible) to restart a recursive process in the middle, if the "program exits" for some reason other than completing its task normally. Then, to be able to "pick up where it left off", the program needs to save its state to some external file which it can read back in when it is started. Otherwise, how would it know that it didn't finish the previous time?

So, I'd recommend (1) understanding what combustion's code is actually doing (printing out the password being tested inside checkPassword() should be sufficient, understanding -why- it works that way is bonus), (2) unrolling the recursion into a simple set of nested loops which accomplishes the same thing, (3) being able to save the current state of testing out to a file …

raptr_dflo 48 Posting Pro

Try the following:

// return a non-cost reference
    std::string & access(int row, int column);
    // returns a const reference, second const indicates that the method
    // doesn't alter the grid-instance that you're accessing from
    const std::string & access(int row, int column) const;

    ...

    csv_File & grab(int index);
    const csv_File & grab(int index) const;

If you're still getting compiler errors, provide more of the source code and specify which line is generating the error.

raptr_dflo 48 Posting Pro

The regulars here may well correct me (which would be awesome, btw), but first to answer your question: the point of linked lists is to make swapping elements efficient -- in particular, to swap any two nodes, you'd just swap the next and prev pointers of the nodes and their neighbors, rather than swapping the contents and leaving the nodes in place. You can draw it on paper as a set of boxes with content-values and arrows pointing from each to its previous and next boxes, and swap nodes (or insert, or delete, or whatever else) by erasing old arrows and drawing new ones so that following the arrows results in the correct new order.

Really not related, other than the question about whether to use pointers, because of the need to know a consistent size to allocate and compute index offsets, a polymorphic STL vector<> of objects needs to store pointers rather than instances. A specific example is wanting to store a list of Shape instances, where a specific shape would be an instance of subclass Triangle, Circle, or ZanyShape. You can't specify std::vector<Shape> because the compiler won't know how to grow/index the vector for different kinds of shapes, so instead (since a pointer is always the same size):

std::vector<Shape*> shape_vec;
Circle *c = new Circle(args);
shape_vec.push_back(c);
...

Meanwhile, happy linking!

raptr_dflo 48 Posting Pro

Since you also posted the same question on the tutorial site you referenced above, and the author has responded, there's probably little reason to keep this thread open. Please mark it as "solved" when that's the case, and feel free to let us know what the solution was!

raptr_dflo 48 Posting Pro

It's generally considered bad form for one application to steal events from all other applications. I'm betting (with good cause) that you can do what you need, which means making sure that the keyboard events are passed to your application -before- they're passed to the application that currently has focus ... if you don't want to (or can't) tell the system that your application should keep focus until it says otherwise (or terminates). Depending on why you need the F5 keypress event sent only to your special application, there may be some other way to achieve the same end. I'm not going to pry, but if this were easy to do, the solution would be ubiquitous and well-documented, and probably none of your applications would work correctly because some other application would be stealing the events it wants. :)

raptr_dflo 48 Posting Pro

No trouble at all. Please mark your thread as "solved". :)

raptr_dflo 48 Posting Pro

Glad to hear it! Please mark your thread as "solved". :)

raptr_dflo 48 Posting Pro

Anything is possible, but I can't read minds yet. Please post the current state of your code along with a description of what you're trying to do, what results you're seeing instead, any error messages, and finally whatever specific questions you have.

raptr_dflo 48 Posting Pro

First of all, you search for the father, then the mother, then the father again, then the mother again. It will be more efficient to search for the father first, and grab the auxID and the level at the same time; then repeat for the mother.

That said, I don't recall from your earlier thread how your member names correspond to the order of data elements in your table. So which element to update is unclear, but for each time through the loop of your people-sorted-by-auxID (from the name of your map variable), you wish to assign a sequentially increasing "code" value? Or is it possible that some "people" already have code values, so you need to make sure you start above that? If the former (everyone gets a new code value), then it's sufficient to include an integer counter in your outer loop control:

int next_code;
    for (it4 = IndivAuxIDSortedMap.begin(), next_code = 1;
         it4 != IndivAuxIDSortedMap.end();
         ++it4, ++next_code)
    {
        ...
        receiveLastCode = next_code;
    }

Note the commas separating the items within each functionality block (initialization, termination-expression [no change here], update), as opposed to the semicolons separating them.

If assigning the next_code is dependent on a condition, then instead initialize it to 1 at the beginning, and then increment it immediately after assigning it to a person.

raptr_dflo 48 Posting Pro

As well, I am wondering when I type in a letter, (for example, the letter h), it returns the number 51276552. Is there a way that I can restrict the user to only input a number?

In your code, it doesn't "return" a large number, it actually fails (since "h" isn't a number), and the number in years is uninitialized garbage.

You can check cin for an error condition via if (cin.fail()) { ... } , and if you want to restrict the user, create a loop that reports the error, re-prompts the user and re-inputs the desired value until the value is valid.

raptr_dflo 48 Posting Pro

Heh, the last function looks great. Consider the possibility that (for some reason) you have only one valid button to draw. (Hint: the problem is actually in your Menu constructor, and has been discussed and re-discussed so many times in this forum that there's a sticky topic for it at the top of the C++ topic list!)

If the hint isn't helping, start inserting debug "cout <<" statements everywhere that makes sense, such as at the end of your Button constructor function to print out all the member values. Good luck!

raptr_dflo 48 Posting Pro

And '+' is defined as the concatenation-operator for the std::string class, so

string s = "foo";
    char c = 'a';
    s = c + s;
    cout << s << endl;

would display "afoo"

raptr_dflo 48 Posting Pro

And there's no bigger help than inserting printf/cout statements to show you exactly which blocks of code are executing (and the values of variables too). They're easy to insert and easy to remove. If you want to get fancy you can define your own "logging system" so that you can print out information at various levels of importance, and set the importance level(s) you're interested in.

raptr_dflo 48 Posting Pro

Or, search the forum for "calculator" -- there's a recurring homework assignment on that topic, it will get you most of the way to computing the mean, and from there you can take a stab at the standard deviation.

raptr_dflo 48 Posting Pro

Why do you have a Queue_head pointer (initialized to and compared against zero instead of NULL) when the comments in your header say there are just the two pointers frontPtr and backPtr? Just use those. Also, if you're going to track Size separately, then you should initialize it in your constructors and update it in enqueue and dequeue.

raptr_dflo 48 Posting Pro

Back to your question, though, you need to implement the Polynomial constructor taking arbitrary coefficients (inserting code in your "main file" before line 17) ... the code in the following variant of the constructor (lines 20-27) is already close.

You also need to implement polynomial addition in method operator+().

Finally, it looks like your operator<<() and operator>>() aren't parallel (you output a different format from the one you input), though that may be intentional.

raptr_dflo 48 Posting Pro

I use a really nice free color-grabber utility on Windows, so haven't bothered coding my own. I'd recommend searching for "keyboard focus" ... since you want your program to keep grabbing keyboard events even while other applications are in the foreground.

raptr_dflo 48 Posting Pro

I wrote a fairly substantial two-way socket-based communication program over a year ago. If you have a basic client-server model working (server listens for connections on a particular port, client [or multiple clients] opens socket connections to the server's port, issues a command, reads until a response returns, and then maybe issues another command, and so on, and closes the socket when done), then you don't need to "reverse" much.

Assume that the "client" still controls the socket connection and will close it when finished. Then in order not to block while waiting for input, each side needs a loop that checks whether there is input waiting to be read or output waiting to be sent. If the socket communication is placed in its own thread, then a queue can be used to store up outbound messages until the socket loop is ready to send them. If there's any chance that data in one direction could prevent data from going the other way in a timely manner, then use a flag variable to switch between "check for something to receive" and "check for something to send" and bounce back and forth each time through the loop. Getting the code correct is not trivial! See how far you can get with this much. Good luck!

pissman commented: Very good ! and helpful +0
raptr_dflo 48 Posting Pro
raptr_dflo 48 Posting Pro

At line 12 of your code, you wrote "I don't know that part" (sorry, the line numbers won't match up here):

while((entry = readdir(dp)))
{
    ... I don't know that part
}

The responder provided code that solves your problem, specifically at line 21:

while ((dirp = readdir(dp)) != NULL) {
    files.push_back(string(dirp->d_name));
}

Read one line at a time. Understand what that line does. Then move to the next line. If you can't figure out what a particular function does, look it up. Then go back and look at a block of lines (surrounded by {}) and understand what the block does, and so on, until you understand the whole program. Unfortunately, there's really no good alternative that will help you learn programming. You can try to delay it, and get people to write specific code for you for a while, but sooner or later you'll actually want to be able to do it yourself, and to do that, you'll have to learn first. DaniWeb is here to help! ... as are plenty of other online resources, but I like this one. :)

raptr_dflo 48 Posting Pro

Ryamjones,
If you haven't discovered it yet, the code (as you posted it) has an extra right-brace at line 35 or 36. But that would cause a compile-time error.

As has been suggested in several other threads here, consider using getline() to read each line from your input into a string, then creating an istringstream from the string and reading your values from that. This will eliminate the need to clear cin.

raptr_dflo 48 Posting Pro

There's a very suspicious "endl" being output in your center() function. Instead, I think you want to output a certain number of spaces, then the passed-in string, then another certain number of spaces, so that you've filled the width of the column.

raptr_dflo 48 Posting Pro

You could certainly use a SQL database. There's no real concept of a C++ d'base, specifically. Instead, you might just want to start with reading/writing a simple text file, as murnesty suggested -- one line per row in your table, and elements in the row separated by comma (or any other character that doesn't show up in your actual data -- you will have all kinds of problems if you try to separate columns by commas and then have commas in your data -- there are workarounds, but the headaches for a relatively new programmer aren't worth it!)

As far as a GUI (graphical user interface), I've been working with Qt for a while now and am quite happy with it. It makes displaying and editing the data in a grid-style table very simple, but the object-oriented nature of separating the data "model" from the "view" can take quite a bit of getting used to! There are other GUI APIs as well, wxWidgets is one which is widely used in Windows and cross-platform.

raptr_dflo 48 Posting Pro

It would greatly improve readability if you used consistent indentation in your code. That said, one very likely problem is the usage of mapface.erase() within the loop of the iterator over items in mapface. Since you pick your range of elements from mapface as the first N with the same index-pair as the first element, use the data and delete those N, the loop increment step of it++ increments from a now-non-existent element to it's possibly-also-non-existent next element.

Since you're always looking at the first element, your outer loop doesn't need to loop over the elements in mapface, and since you always delete something, can be simplified to while (mapface.size() > 0) {...}.

At lines 27 and 28, it might be more readable to define the face object first, add the AdjacentCells to it, then push it onto the array:

...
Face face(points[ip1], points[ip2]);
face.pushBackAdjCells(ip3);
faces.push_back(face);
...

though I don't think there's anything technically wrong with what you have now.

Try that much, and get back to us?

raptr_dflo 48 Posting Pro

You print out some of the values of the next line of the transaction file only if the current transaction number equals the current customer number.

Your loop now reads a line out of the masterfile and a line out of the transactionfile, and prints one of "Transaction#..." (and some of the values from the current line of the transaction file) only if the transaction customer number equals the masterfile customer number; otherwise it prints "Invalid matching...". Either way, the line is followed by "Balance due:...", right?

If you're not seeing this, please provide your two input files, and the output you're seeing, it might help determine what's going wrong.

raptr_dflo 48 Posting Pro

It looks to me like your output so far is correct. The "map" type isn't going to help you with your task, it just provides a space-efficient way of storing an indexed list of objects. Instead, you will want to traverse the tree structure you've built up. Specifically, for parents to have lower ids than their children, you will probably want to use a pre-order traversal of the tree: visit and handle both parent nodes before the individual, recursively. The simplest thing may be to fix the ID of a node and assign it into a new map, both at the same time, then delete the old map when you're finished.

raptr_dflo 48 Posting Pro

At some point in your code, you need to assign a value to TotalCS.

TotalCS = <something>;

So far, all you're doing is inputting values into variables and printing out expressions. Either you've been asleep in your course, or you're just in a panic now. Take a deep breath, and think through what you're doing. Everything will go a good bit easier as a result. :)

raptr_dflo 48 Posting Pro

Naveen12,
Please do not add questions to solved threads. Instead, create a new thread, re-posting your code with any specific questions. Thanks!

raptr_dflo 48 Posting Pro

Well, since you know how to solve the problem for 4 and 6 disks, think about what are the legal and illegal moves, from the current state, and especially which pairs of moves make no sense (moving a disk from A to B and back to A accomplishes nothing).

To do this, you will need to represent the current state of which disks are on which pole (in which order, though by the rules the order should always be smallest on top, increasing towards the bottom), what move was just made (so you don't undo it), what moves are allowable next, and the brain power you used to solve the 4- and 6-disk problems by hand. So you may want to have classes like Game and Move. A Disk class probably isn't needed (an int is sufficient), same for a separate Pole class (you can use a std::vector<> and add and remove items only from one end).

The "algorithm" for moving the disks is just what you figured out. Say it out loud to yourself as you do it: for each disk you move, why are you moving that one instead of another one? Why are you moving it to the pole you've chosen instead of the other option? It should almost code itself....

Good luck!

raptr_dflo 48 Posting Pro

Now that we know what you're actually trying to accomplish, let me google that for you:
http://lmgtfy.com/?q=hash+table

raptr_dflo 48 Posting Pro

Check out the 'curl' package. It should at least get you started.

raptr_dflo 48 Posting Pro

>> which would presumably be 256 in this case?
why 256? sizeof(double) != 256, so where did you get that number?

It has nothing to do with the magnitude of the double, or the memory allocated to store it. I'm assuming the OP is taking the modulo of (int)(original_value) % size to limit the range of output values. 256 would be the max-value-plus-one of an 8-bit ASCII value the OP was hoping to convert to.... Or he could use 128 instead to get a 7-bit ASCII result. For what it's worth....

Minimally related, the integer portions of large float/double values can't be represented by the int type. My test here returns INT_MIN (from limits.h) for float f = 3e12; int i = int(f);

raptr_dflo 48 Posting Pro

And to the OP, you already have code, what seems to be the problem?

raptr_dflo 48 Posting Pro

That makes no sense. If T is type double how is the function supposed to convert the double to a single ascii character???

Um, presumably by taking the modulo of the integer part against parameter size , which would presumably be 256 in this case? ;)

Not saying it makes much sense, still, but it should "work"....

raptr_dflo 48 Posting Pro

In prey::breed(), you check whether moves==3, but you don't reset it to zero, so that prey instance will never breed again. You probably have similiar problems in the other methods.

While I was looking I also noticed that you randomly place prey and predators in the constructors, but don't check whether the space is empty. You should have a loop that checks for that. Keep in mind that if your choices of 3 and 8 don't make sense, the grid may become over-populated, and then the loop may take a while to pick a random location which is still empty, or will eventually loop forever. Take this into consideration -- I don't want to tell you a way of doing this yet, see if you can figure out something for yourself first. You also place the name of the prey (and where does that come from, you don't have a name yet when you call prey::prey()!) into the grid at the corresponding location, but not the name of the predator, is that intentional?

Finally, your random-movement logic in prey::move() is flawed: since you're picking a random number each time, there is a substantial chance that you won't pick any direction at all. Instead assign rand()%4 to a temporary variable, and then check that variable to decide which keystroke to use for it. Or initialize an array int keystrokes[] = {119, 115, 100, 97}; and then you can use the temporary variable (or even rand()%4 directly) as an index …

raptr_dflo 48 Posting Pro

Not to pry into your personal business, but why would you want to do this, besides to spam somebody else's site?

If you've been tasked with data entry to pre-populate a website, it would make more sense to enter the data into the back-end of the website, rather than through the front-end.

If you've been tasked with testing the front-end by inputting a specific set of data, there are various website test suites that could help you with your job. Try Google.

Anything else?

raptr_dflo 48 Posting Pro

As has been discussed in many other threads here, "cin >>" doesn't remove the end-of-line from the stream after you read in the zero or one. So I'm thinking the getline() at line 21 gets the now-empty line and writes it to the file, rather than waiting for a new line of input.

Instead of cin >> n1; at line 16, try:

#include <sstream>
...
string line;
getline(cin, line);
istringstream is_strm(line);
is_strm >> n1;
raptr_dflo 48 Posting Pro

For what it's worth, I'm running Vista and Windows 7 here (on separate laptops), and each has a "Manage Wireless Networks" item, rather than "View Wireless Networks". Also each has a vastly superior manufacturer-provided interface: "Dell Wireless WLAN Card Utility" and (untitled custom-chromed window, accessed via "Lenovo's Internet Connection" link from "Network and Sharing Center").

On my Dell/Vista box, Process Explorer shows the Microsoft "Manage Wireless Networks" dialog as being a variant of Windows Explorer (with specific command-line arguments passed to have it display its contents):

"C:\Windows\explorer.exe" /e,/root,::{21ec2020-3aea-1069-a2dd-08002b30309d}\::{1FA9085F-25A2-489B-85D4-86326EEDCD87}

I fear those weird long strings are being fetched from the registry, good luck with that! Or maybe, as you suggested, there's a short-cut or wrapper program somewhere that's easier to invoke.