raptr_dflo 48 Posting Pro

Cool! If/when you're all set, pease mark this thread as "Solved". :)

raptr_dflo 48 Posting Pro

Found this thread on google (search: "CMainFrame LoadFrame"): http://www.codeguru.com/forum/archive/index.php/t-397306.html -- comments towards the bottom might be especially helpful: make sure you're correctly calling PreCreateWindow, and/or CMainFrame's Create() method may be preferable to calling LoadFrame() inherited from CFrameWnd.

raptr_dflo 48 Posting Pro

At lines 20-27, you've already declared the return-types and argument types of the functions (up at the very top of your program). Now you just need to call the functions and capture the return types, for example:

greeting();
getInput();
int result = calculate(num1, num2, num3, num4);
...

Also, your getInput() function doesn't do anything useful, because you re-declare the four values locally (within the function) and then read them in. The local variables are destroyed when the function returns. Instead, try:

void getInput(int &num1, int &num2, int &num3, float &num4);
    // return type is void, if the function doesn't return a value
    // note the '&' on each argument ... passing references (rather than copies)
    // means that changes made inside the function (like inputting values) will
    // be saved in the original variables, not the copies

...
getInput(num1, num2, num3, num4);
    // no '&' here, that's just how the function is declared

...
void getInput(int &num1, int &num2, int &num2, float &num4)
{
    // parameters are declared above, no local variables needed
    // also, get in the habit of using consistent indentation, it will make your
    // code more readable for you and for others
    printf("Enter three integers and a floating point number then press enter: ");
    scanf("%d%d%d%g", &num1, &num2, &num3, &num4);
        // no spaces needed in the format-string, scanf() will automatically
        // skip over spaces in the input
        // also note the '%g' format for the float variable
    return;
}
raptr_dflo 48 Posting Pro

The error is occurring because CWnd::Attach() is requiring an internal window-handle object to be NULL ... that is, presumably, not already initialized in some other way.

I suspect your problem may be that you're calling pMainFrame->LoadFrame() more than once (maybe inside a loop?), or possibly making some other call that initializes CWnd's internal window-handle object.

If you still can't figure it out, please post a bit more of your own code (especially preceding the 2 lines you've provided so far). Thanks!

raptr_dflo 48 Posting Pro

Right near the bottom, you're looping for 5 seconds, but do you have 5 seconds worth of audio in your .wav file to read in? Probably, it's only 5 seconds....

Also, from your earlier question, you're still reading audio data from stdin ... how are you getting the data out of the .wav file? It's not just raw audio samples (see the previous comment), so you can't do cat sound.wav | my_sound_player.exe . Look up how to read data from a .wav file (or find and use an existing library).

raptr_dflo 48 Posting Pro

If you're storing credit-card numbers, you may also want to encrypt the data (or the entire XML file) in addition to signing it. ;)

As far as generating public and private keys, I recommend PuTTY: http://www.chiark.greenend.org.uk/~sgtatham/putty/

raptr_dflo 48 Posting Pro

DLLs require Windows-specific declarations on each function you want to have accessible. As far as I know, these extra declarations do not impact your ability to access the functions if built into an .exe:

int someFunction(int someArgument)
{
   ...
}

becomes

extern "C" __declspec(dllexport) int someFunction(int someArgument)
...

Then to create the DLL in VisualStudio (if that's what you're using), I recommend starting a new project with the type-stuff pre-set-up to build a DLL, then import your same source file into the new project. There are probably ways to set up switches so that a single project builds everything you need, try poking around on msdn.com. Good luck!

raptr_dflo 48 Posting Pro

Yes. See moschops' response previously. If you want a useful answer, please ask the correct question. And demonstrate that you've tried to solve the problem yourself before asking us how to do everything.

If DDE Server is to be part of your program, I don't know anything about its API, where to download a library or how to install it. If DDE Server is a separate running process, whether on your own machine (127.0.0.1) or some remote machine, then presumably there's a well-defined protocol for communicating with it.

raptr_dflo 48 Posting Pro

Break your problem up into small easily-managed pieces. You're off to a good start, you can create an empty grid, and you can print out your grid. What do you want to do next? Programming can seem overwhelming if you're trying to solve everything all in one step. Pick a step, describe what the step is (if you can't describe it to yourself, or can't code it from your description, break it up into smaller steps!), figure out how to test whether you've coded it correctly, then code-test-repeat until it's working. So what's your next step? Put some predators and prey on your grid? Do that much. Test it by printing out the resulting grid.

raptr_dflo 48 Posting Pro

If you're creating your own vector template class, then the forward declaration is:

template <class T> class vector;

And depending on your compiler, the entire source for the template class may need to be included into the same file (specifically, you may not be able to separate the prototype into a vector.h file and the implementation into a vector.cpp file).

Unless you're also writing your own string class, then you have to include it -- it's not part of the C++ language, it's a class written in C++:

#include <string>
using namespace std;

string myString;

or

#include <string>

std::string myString;
raptr_dflo 48 Posting Pro

Why does your ExpPow function ignore the "count" argument? Start there, and think about what it really needs to compute.

Then think about your negexp function: how does the result of a negative exponent compare to the corresponding positive exponent? Can you make use of that by having one function call the other?

All the other looping in your main() is an indication that you're not thinking about the functions -- you only need one loop in main, the way you started.

raptr_dflo 48 Posting Pro

A couple of additional tips:

For your own sanity, consider using the C++ string type instead of character-arrays:

#include <string>
...
std::string str;

Also, there's nothing in your Deque class to indicate how the nodes in your queue are connected to each other, or how the deque keeps track of the ends. You may want to define two classes, perhaps called Deque and DequeNode . Don't forget about the "circular" requirement -- what does that mean as far as pushing nodes onto the ends of the deque?

Almost all of the demonstration can be accomplished by printing appropriate messages from within the "big 3" memory management functions, and then showing that the correct messages are printed for various calls, e.g.:

cout << "Instantiation does not use the copy constructor:" << endl;
cout << "DequeNode t = s;" << endl;
DequeNode t = s;
cout << "DequeNode t(s);" << endl;
DequeNode t(s);
Nick Evan commented: Excellent suggestions +16
raptr_dflo 48 Posting Pro

Also, your input data file already tells you which row and which seat each person is in. Since you have that information, you might want to create a new array of seats, where each person is placed in the correct position:

Person *seats[10][3];
// TODO: initialize to NULL values

for (int x = 0; x < 41; x++) {
    row = manifest[x].row;
    seat = manifest[x].seat;
    if (seats[row][seat] != NULL)
        cout << "somebody already sitting in row " << row << ", seat " << seat << endl;
    else
        seats[row][seat] = &manifest[x];
raptr_dflo 48 Posting Pro

various input on books here: http://stackoverflow.com/questions/366317/good-data-structures-text-book. I can vouch for Aho, Hopcroft, Ullman -- but like other commenters, it was my college text over 20 years ago. And definitely -not- C++-specific. The good news is, data structures are virtually identical in every programming language, so the primary purpose is to understand the structures, how and when to use them, and what's involved in a complete and correct implementation, regardless of the programming language of choice. Also from the top of this C++ forum: http://www.daniweb.com/software-development/cpp/threads/70096

raptr_dflo 48 Posting Pro

No, I don't have anything already written, I'm pretty sure I made that point as well. :) As far as data structures, I'd recommend grabbing a book. I bet there's a decent "Data Structures in C++" book on the shelves of your local book store, or they'd be able to point you to another store to try.

Rather than trying to come up with code that you can understand, which solves your problem, I'd prefer that you actually take a bit of a break (if you need) and learn more about programming in general ... then when you go back to reading specifically about "recursive descent parsers", it'll make more sense to you, and you'll have a much better idea how to approach the problem code-wise.

Not that it helps much now, but you can think of your equations in a hierarchical sense:
+ an equation is made up of expressions on either side of an '=' sign (*)
+ an expression is a sequence: operand, operator, operand, ..., operand.
+++ an exception to the above is the unary "negation" operator which doesn't need a preceding operand.
+ operators include +, -, *, /, ^ (others too, i bet)
+ operands can be numeric constants, variables, or other expressions (**)

(*) in fact, you can think of the entire equation as a single expression, where the "=" (along with "<", ">", etc.) is a "relational operator" -- one that returns true or …

raptr_dflo 48 Posting Pro

Detecting '^' is no different from checking for any other operator. The problem you're more likely to be running into now is implicit operator precedence. In the simplest case, if the user types in "3 + 5 * 2 = x", you need to make sure that you're doing the "5 * 2" part before the "3 +" part. Same for '^', that will have to come before "*/" or "+-".

As far as detecting more variables than "just x" ... if you want the user to be able to use "y" instead, then it might be as simple as "if it's not a number or an operator, then replace it with x" and continue as you do now. If you want to remember that it used to be y, save it in a separate variable, and replace it when you print out the result:

string actual_var = "";
    if ((strtream(n2) >> n2_val).fail()) {
        actual_var = n2;
        n2 = "x";
    }

    // do rest of equation solving here

    if (actual_var != "") {
        cout << actual_var << " = " << answer;
    }
    else {
        cout << "answer = " << answer;
    }

If instead you want the user to be able to input something like "y = 3 * x + 5", that's a whole other level of code management, and you're not approaching the problem in a sufficiently scalable manner -- what are you going to do when you're ready to read something like "z = …

raptr_dflo 48 Posting Pro

Hey thecoolman5, don't worry if my code-block doesn't make sense yet, just go back and look at it once in a while. It's a good beginning to your question about "what if the user doesn't type in spaces?" but isn't necessary at this point. And what you'd do with it, as far as solving the equation, is similar to what you're already doing. With the added benefit that you've already determined whether each item is a number, a variable, or an operator, so you can detect whether the user typed in something that doesn't make sense.

Let me know if you get stuck on something else.

raptr_dflo 48 Posting Pro

Now your tank.update() method apparently moves the rect of the sprite, but the tank.draw() method blits the image at (self.x, self.y), which aren't updated except for the player's tank (via keystroke). If you're going to maintain these values separately, you have to keep them synchronized: whenever you move the rect, update x and y; and vice versa.

You can save yourself most of the confusion by writing smaller programs first: one that allows you to use the keyboard to move your own tank the way you want, and a second one that demonstrates automatic movement of [enemy] tanks. Then when you have both programs working correctly separately, then you can look at merging the main loop into one that takes user input for the player-tank and automates enemy-tanks.

For starters, just have two separate classes: PlayerTank and EnemyTank. Then when you're more comfortable, you can put all the common repeated functionality (like the draw() method, for instance) into a BaseTank class, derive PlayerTank and EnemyTank from BaseTank, and add only the new unique members and methods to each of the derived classes.

If anything can move diagonally, there are some good comments under rect.move() and rect.move_ip() at http://www.pygame.org/docs/ref/rect.html#Rect.move

raptr_dflo 48 Posting Pro

How does your code determine if the player has hit a wall while moving? Worst case, try moving a temporary fake object in a straight line (or approximately straight anyway)from the enemy to the player (all at once in a loop, rather than making one movement per simulation cycle) and see if you bounce off a wall on the way.

raptr_dflo 48 Posting Pro

You've already clearly explained (in English) what you need to do, now translate that into code.

pseudo-code here:

for enemy in enemies:
    is_wall = determine if there is a wall between enemy and me
    if is_wall:
        # do nothing
        continue
    dist = compute distance between enemy and me
    if dist > max_shooting_dist:
        move enemy a little bit towards me
    elif this enemy hasn't fired recently:
        shoot a bullet towards me
        add the bullet to a list of enemy bullets so we can keep updating its position

Do the parts you can, then get back to us with your version of this block of code, and what detail you're stuck on.

raptr_dflo 48 Posting Pro

We (or I, anyway) still don't really understand what it is you're trying to achieve. If you could include a small sample .csv file that you generate using your code, and then show us what you think it should look like instead, rather than speaking in abstractions, maybe that would help.

raptr_dflo 48 Posting Pro
raptr_dflo 48 Posting Pro

What happens if you input -6? It looks to me as though your program will tell me it's odd.

Try thinking through your problem out loud. If you can tell yourself logically how it should get to the answer, you should be able to program it correctly.

For starters:
"If my number is positive, i can keep subtracting 2 from it without changing the answer, and will eventually get to 0 (if it was 2, 4, 6, ...) or -1 (if it was 1, 3, 5, ...)."

Now include negative numbers as well. Good luck!

raptr_dflo 48 Posting Pro

Your problem is that once you remove the shortest distance from your distances array, when you search for the next-smallest distance, the index matches your cities list only if it comes before the previous one. If it comes after, you're looking at the wrong city. I think you can fix the problem by deleting the cityname at the same time as the distance -- since distances.index(shortest_distance) is already assigned to closest_city , try:

...
    del distances[closest_city]
    del citynames[closest_city]

You don't need "+count" when you print your cityname, except that your (inadvertently?) extended onto the end of the same array at the top of your program (for x and y, you use different array-names). Note: all that reading code is still completely ugly, but at least this should get your program working as expected.

raptr_dflo 48 Posting Pro

Finally got a chance to finish this up for now.... Sorry for the confusion about the spaces, thecoolman5! I promise I'm not trying to make you crazy. :)

If you want to avoid entering spaces, we're back to some of the previous parsing code. C++ has no way of knowing, when you're inputting a string from the user, that "22+x=5" is actually 5 tokens: the integer 22, an operator +, a variable x, an operator =, and the integer 5. We're lucky it breaks on whitespace, but you have the same problem on the other side if you want to know -what- whitespace the user typed in, or if you want to keep it for some reason.

So, for your case, you would instead use getline(cin, expressionString); , and then go through the string yourself, deciding whether the next character is part of the previous token, or indicates the start of a (potentially-single-character) new one. If this were already a solved problem, within the language, there'd be no point for you to be writing your own, right? :)

If you're not comfortable with the math conversion functions in stdlib, and want instead to handle them yourself (which is completely fine, and will certainly advance your programming skills), here is a loop over the string input above that handles positive integers:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main (void)
{
        cout << "Enter an equation: n1 op n2 op n3" << endl
             << …
raptr_dflo 48 Posting Pro

and now the thing won't compile

Heh, I still can't read minds. What error(s) are you getting, and what does the code look like in the vicinity of the problem? The great thing about compiler errors (assuming the compiler is worth anything) is that it tells you what it doesn't like and at what line. Much easier to fix than run-time problems, usually! :)

raptr_dflo 48 Posting Pro

Lol, it doesn't "think" of a new number, it's a predictable formula -- thus "pseudorandom" rather than truly random -- and it takes all the time it needs. You keep getting the same number(s) because you keep resetting it by calling srand() inside your loop. If you want to loop over the set of integers between -rr1 and rr1, in a random order, there are a couple of options. See if you can follow the example at http://www.cplusplus.com/reference/algorithm/random_shuffle/ to do what you want. BTW, cplusplus.com is an -outstanding- reference especially for the standard template library (STL).

raptr_dflo 48 Posting Pro

Also, the numbers generated are "random" ... meaning at some point you're more likely to get a number you've seen before than one you haven't seen yet. If you want to "cross off" numbers you've seen before, you need to implement that yourself: rand() generates numbers out of a huge set, and it doesn't know about the math you're performing to map those onto a relatively small set, so even if you could tell rand() not to repeat itself, huge swaths of unique numbers would still map onto the same number in your code.

raptr_dflo 48 Posting Pro

Yes, so seed the random-number-generator (by calling srand(time(0))) only once ... ever ... and then just call rand() each time you need a new random number. Think of srand() as a reset() (which is what it is) ... each time you call it with a specific number, it will start over, giving you the same sequence of random numbers again.

raptr_dflo 48 Posting Pro

Real quick, you have an infinite loop starting at line 30 above, and another one starting after you check that n1 and n2 are both x and you get n3 and the random number range, starting at line 47.

Also, you don't need to reseed the random number generator for each number, just call srand() once, before you ever start looping. Since it looks like lowest, highest and range don't change, you can also declare and assign those outside your loop, and there's no benefit to assigning r1=rand() and then re-assigning it three lines lower (same for r2).

Does any of that help?

raptr_dflo 48 Posting Pro

thecoolman5,
I got started on another parsing loop for not-requiring-spaces-between-tokens, but got dragged away from it, will try to get back to you today. As far as the random numbers, feel free to post just the relevant lines of code near where you assign and print the values, and I'll see what's going on.

raptr_dflo 48 Posting Pro

Hmmm.... Sorry, I have no clue why the same code would work as expected for me -- at least acting like it's breaking the input on whitespace and assigning the variables in order -- but not for you.

For what it's worth, I just tried inputting and outputting only n1 (of type string ), and typing in the space-separated formula x + 3 = 5 , and the output gave me just "x". So it would appear that istream does break on whitespace....

raptr_dflo 48 Posting Pro

Did you include spaces between the items? You may need to....

raptr_dflo 48 Posting Pro

Describe "didn't work". I just wrote, compiled, and tested the following, and it worked just fine:

#include <iostream>
#include <string>
using namespace std;

int main (void)
{
        string n1, n2, n3;
        char operators, operators2;

        cout << "Enter an equation: n1 op n2 op n3" << endl
             << "n values can be integers or variables" << endl;

        cin >> n1 >> operators >> n2 >> operators2 >> n3;

        cout << "You typed: " << n1 << " " << operators << " " << n2 << " "
             << operators2 << " " << n3 << endl;
}
raptr_dflo 48 Posting Pro

To get multiple things on one line, try:

cin >> n1string >> operator1string >> n2string >> operator2string >> n3string;

or maybe

getline(cin, cppString);
stringstream theStream(cppString);
if((theStream >> someInt).fail())
    cout << "Invalid number, woops!" << endl;
else if((theStream >> operator1).fail())
    cout << "Couldn't get first operator" << endl;
else if((theStream >> n2).fail())
    cout << "Invalid 2nd number" << endl;
...
raptr_dflo 48 Posting Pro

As I suggested previously, feel free to remove the "const" wherever you have "const char *" in your code ... it adds extra checking for "correctness", but isn't strictly necessary, and it's wreaking havoc with your use of the C functions from stdlib.h.

As WaltP pointed out, you can't (usefully) change the declarations in the standard headers: those tell you what the default libraries are expecting to receive so that you can compile against them -- think of them as read-only, and provide what they indicate. In this case, atol() doesn't take single characters, it takes C-style strings (arrays of characters with terminating '\0' characters. A quick-and-dirty approach is

char n1_str[2];
n1_str[0] = n1;
n1_str[1] = '\0';
int n1_val = atol(n1_str);

but as I said before, using single characters for n1, n2, n3 means you can't use multi-digit numbers like 10 or 22.

I'm going to go way out on a limb here, and suggest that if you can't fix errors that say a given function expected a "char **" instead of a "const char **" and/or don't even understand what those errors mean, then you're in way over your head here. In answer to your earlier question to the effect of "why can't C++ just handle the strings" ... it can -- it's a process called parsing, and it's what we're working on here. It's a pain in the ass, and the code I've provided to date probably isn't 100% correct yet, but since we can't …

raptr_dflo 48 Posting Pro

Well, despite my best efforts, I can't yet read minds. Post up the code you have at this point, and I'll at least try to figure out why it's crashing. And we'll see where to go next.

raptr_dflo 48 Posting Pro

There's so much weird stuff in your code now, I'm not sure where to begin. But I'll start with line 106 above, where you assign a new Tank instance with the same name as the class, making the class inaccessible from that point forward. You also create new tanks by passing a position tuple and assigning it to center , and then using x and y everywhere else. Maybe the pygame.sprite.Sprite class uses center ? If so, save yourself a lot of headache and use it also. Finally it looks like you're using the right and left arrow keys to change the driection of the non-npc tank starting at line 32, and also to tweak the position of your poorly-named Tank instance starting at line 145. One or the other is presumably in a debugging state, but consider commenting out or removing code you're not testing, until you get basics working, and then add it back in when you're ready to proceed to the next step.

raptr_dflo 48 Posting Pro

Well now your update of initial and new_clock (and computation of elapsed ) are outside your moveBall() loop. Since the first two values are assigned on successive lines, so little time elapses between successive calls to clock() that they probably have the same value, making elapsed 0.0. This would certainly keep the ball from moving, according to the formulas you use in moveBall().

raptr_dflo 48 Posting Pro

Hey thecoolman5,
I have cygwin and mingw32 installed on the machine, but unfortunately it's a 64-bit Win7 box, and for whatever reason, the mingw version of g++ is really unhappy in that environment. I've been meaning to fix it forever, but my actual "work" is purely in Python now, so it's not a job requirement to get to it. ;)

MAX_OPERANDS was for you to define, you clearly know how (?) from your previous code. True and False are the Python versions, sorry, C++ uses true and false (lower case) ... the dangers of working in multiple languages! You can remove the "const" from next_ptr at line 25. Since I'm not changing the string, I think declaring it const is the "correct" thing to do, but the declaration of strtod doesn't want it. It might also depend on whether you're hitting the strtod() from stdlib.h (which is C, and predates "const"-ness) or std::strtod() from cstdlib. And probably more. Anyway, my point was to illustrate how you could work with more complex structures and arrays to simplify your code and make it more readable and maintainable.

Anyway, you don't want to "redeclare" your variables (presumably within an enclosing block, otherwise you'd get a compiler error). What you're actually doing in that case is creating a new variable (with its own memory) with the same name as the previously existing one(s), thus "masking" the previous ones (and making them difficult or impossible to access within that block). The extremely …

raptr_dflo 48 Posting Pro

In Linux, something like:
prompt $ gcc -g server.c -o server
prompt $ server 12345

If you're using VS on Windows, you need to add the argument somewhere in the settings. Or after you build server.exe, open a Command Prompt window, cd to where server.exe was placed, and then:
prompt $ ./server.exe 12345

If that isn't working, what error are you getting? Maybe the problem isn't with the argument.

raptr_dflo 48 Posting Pro

temp is defined as type char at line 6. result is an instance of class string . There is no string.insert() method variant that takes a char argument, so the author used

string& insert ( size_t pos1, const char* s, size_t n);

which takes an array of characters (or a pointer to a character, same thing in C/C++) and a length (in case the character array or string, same thing in C) is not null-terminated. He is then passing a pointer to the character temp , which he creates by using the address-of operator & . Since he doesn't have a null-terminated array of characters, he also passes 1 to indicate that the "string" is just the one character in length.

tux4life commented: Great explanation :) +14
raptr_dflo 48 Posting Pro

I don't know why you're using variables zero and one in addition to replpos , so first of all, <frequent advice>slow down, think through what it is you're trying to do, say it out loud or write it down clearly in English (or your natural language of choice), and then code it from there.</frequent advice>

In your case, you're looking for and replacing successive digits. While you can certainly do this in-place in a single string, it might be simpler to build a second string while you go through the first.

However, your algorithm should be something like:

while i'm not at the end of my string:
    find the next zero or one, whichever comes first
    if it's a zero:
        replace it with the zero-replacement string
        advance the position by the length of the replacement
    if it's a one:
        replace it with the one-replacement string
        advance the position by the length of the replacement

I think you have an off-by-one error in your increments, you only need to update replpos, and instead of two different blocks (which, the way you have them now, will only work if successive values of 0 and 1 alternate in your original string), you need to do two separate finds and keep the answer with the smallest position. Does that make sense?

Aside: if your replacement strings are all different lengths, you may have quite a challenge reversing your "encryption". As an overly simple example, if you encode 'a' by 123, …

raptr_dflo 48 Posting Pro

Well it looks like you've done enough to get a buffer of ALint values. What is the range of possible valid values in that buffer? Then normalizing to float is as simple as:

float intermediate_value = (i_val - min_ival)/float(max_ival - min_ival);
float f_val = min_fval + intermediate_value*(max_fval - min_fval);

If the integers, for example, all lie between 0 and 65535 (16 bit unsigned integers), and you want floats between -1 and 1, then the values are

int min_ival = 0;
int max_ival = 65535;
float min_fval = -1.0f;
float max_fval = 1.0f;

Keep in mind: expressions which don't change can be evaluated once, and multiplication is often faster than division. Though a really good optimizing compiler will take care of it for you.

raptr_dflo 48 Posting Pro

Now that you've created a mapping of your input file and output file, what do you intend to do with each? You don't call isPalindrome() anywhere, nor does it look like you even iterate over your input mapping or set anything in your output mapping.

Has anyone asked why you're memory-mapping the files in the first place, instead of simply reading out of an input file and writing into an output file?

raptr_dflo 48 Posting Pro

Are you pressing the arrow keys? Your logic for moving the ball requires that a key be pressed to move the ball in that direction.

I suppose the clock() will eventually wrap around, so you need to understand what the maximum value of clock() could be and handle it:

new_clock = clock();
    if (new_clock < initial)
        // (new_clock + MAX_CLOCKS) - initial, but re-ordered to avoid overflow
        delta = (MAX_CLOCKS - initial) + new_clock;
    else
        delta = new_clock - initial;
    elapsed = double(delta) / double(CLOCKS_PER_SEC);
raptr_dflo 48 Posting Pro

Consider what the following might do:

char letter = 'q';
int order = letter - 'a';

...

char other_letter = 'a' + other_order;

And as for your question about reading successive 2-digit numbers:

...
std::string next_num = std::string(string, pos, 2);
pos += 2;
int value = strtol(nex_num.c_str());
...

I'm sure there's a more C++-ish way to do that last line, maybe using a strstream, but I'm old-school and learned C before C++ was stable enough to be usable, so I have lots of "bad" habits.... :)

raptr_dflo 48 Posting Pro

Consider using arrays, to reduce the amount of repeated and nearly identical code:

double n[3], ans;
char operators[2];
int n_index;

cout << "equation: ";
cin >> n[0] >> operators[0] >> n[1] >> operators[1] >> n[2];

cout << "which number do you want to replace with a variable (starting with 1)? "
cin >> v_index;
v_index -= 1;  // index starts from zero

int index_1, index_2;
bool reverse_operators = False;

// assuming the second operator is the '='
if (v_index == 0) {
    index_1 = 2;
    index_2 = 1;
    reverse_operators = True;
}
else if (v_index == 1) {
    index_1 = 2;
    index_2 = 0;
    reverse_operators = True;
}
else {
    index_1 = 0;
    index_2 = 1;
}

if (operators[0] == '+') {
    if (reverse_operators)
        ans = n[index_1] - n[index_2];
    else
        ans = n[index_1] + n[index_2];
}
else if (...

Now to be more generally useful, you'd like to be able to detect variables (and eventually function names like 'sqrt'), and it would be good to be able to find '=' signs as well.

The std::string class is a good place to start, and cstdlib functions skip over whitespace, so you can just read in a whole line once, and then see what you have.

// TODO: make tokens[] a dynamically growable array
std:string line;

cout << "Enter equation: ";
getline(cin, line);

const char *line_chars = line.c_str();
const char *line_ptr = line_chars;

// assuming the only options are numbers, variables, and the operators +-*/=
// and that they …
raptr_dflo 48 Posting Pro

Hialek, at least one problem is in lines 27-30 of your code:

if(c=='\n'){
    items.push_back ( vector<int>() );
    i++;
}

The first time through, you don't have anything in items (assuming you don't have a blank line at the start of your file). The first time you do get a '\n' you add a first item (items[0]) and then immediately increment i so that at line 33 you're referencing items[1], which doesn't exist yet.

An approach like ravenous' will probably save you a lot of headache. Fill a single item object at a time, and when you get to a '\n' push that onto the back of your items vector and create a new item.

raptr_dflo 48 Posting Pro

Since you're presumably supposed to be writing your own stack implementation (using a singly-linked list) as part of your assignment, I'll start with your first few lines:

struct stack{
    stack s1,s2;
    int info;
};

First of all, you can't declare s1 and s2 to be of type stack because you have not yet declared a type called stack . You would need to specify struct stack which you have declared.

Second, if you could recursively include a struct stack object within itself (which I doubt), you wouldn't want to. I think what you want here is a pointer: struct stack *s1, *s2; Third, since you're supposed to implement your stack using a singly-linked list, a node should have only one pointer in it, not two.

Fourth, simplify your understanding by separating the notion of a node in your linked-list from the notion of a stack (which wraps your linked-list with a specific set of allowable operations).

struct linkedListNode {
    int info;
    struct linkedListNode *next;
};

typedef struct linkedListNode LinkedListNode;  // notice the leading upper-case "L" for the type!

class Stack
{
private:
    LinkedListNode *top;
public:
    Stack();
    void push(int value);
    void pop();
    int top();
};

Stack::Stack() :
    top(NULL)
{}

void Stack::push(int value)
{
    LinkedListNode *newNode = new LinkedListNode();
    // TODO: check for allocation error here!
    newNode->info = value;
    newNode->next = top;
    top = newNode;
}

...

And that's just the from the first four lines! Try harder to think through what task(s) you need the program to …