Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I suspect that this is because you are tyring to print a standard int value with %ld, the formatting marker for long int. I you need values greater than 2 billion, then you need to declare the variables as long or even long long (depending) as well.

BTW, has this assignment been handed in yet? It's been over a week.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, as we've already said before, you really should change void main() to int main() and have it return 0; at the end of the function.

Second, the way you now have it, the prices for all the cars will be the same, and total price will always be 120,000; the price per day will decrease with the number of days. I think what you want is more like:

 printf("\n You have selected TATA SUMO | %ldrs per day \n ie total %ldRs\n",12000, 12000 * nod);
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I'm more confused than ever, especially with regards to the myStrlen() function. First off, it is getting the size of the array of strings, not any one string itself, so the name is misleading. More to the point, it relies on there being a string at the end of the array consisting of a single null value. But this won't be the case for an array of C++ strings, not without there being an explicit marker! Whe I tested this, it showed that it was indeed going off the array:

int main()
{
    string folks[6] = { "obiwan", "minnie", "han", "simba", "jabba", "ariel" };
    cerr << myStrlen(folks) << endl << endl;
    assert(myStrlen(folks) == 6);
    cerr << "myStrlen() - Test ok" << endl << endl;

    assert(partition(folks, 6, "base") == 1); //return 1 since only the first one “ariel” is less than base

    cerr << "partition() - Test ok" << endl;
}

When I ran it after compiling with MinGW gcc 4.6, the actual size returned by myStrlen() was 9, which means that it was continuing on past the end of the array until it found something that matched the end condition by sheer chance. Similarly, the returned value was 10 when compiled under VC++ Express 2010.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Has your coursework covered data structures yet? You can bundle the car model and price up into a struct type and save yourself some hassle:

struct Car
{
    char make[16];
    char model[16];
    char year[4];
    int price;
};

This let's you have a record of the all the car makes and models which in each category:

const struct Car SUV[] = { 
                              {"Tata", "Sumo", "2010", 9000},
                              {"Chevrolet", "Tavera", "2009", 12000},
                              {"Trax", "Toofan", "2011", 10000}
                          };
const int SUV_COUNT = 3;

You can use these records to display the model and price info for the category:

        case 2:
        printf("\n You have chosen Long Trip Vehicles \n");
        printf("\n Vehicles Available are \n");
        for (i = 0; i < SUV_COUNT; i++)
        {
            printf("%d: %s %s, ", i + 1, SUV[i].make, SUV[i].model);
        }
        printf("\n\n ----------------------------- \n");
        printf("Enter the number of the car model you want: ");
        scanf("%d", &r);
        r--;
        printf("\n You have selected %s %s %s | Cost %d rs per day \n", 
               SUV[r].year, SUV[r].make, SUV[r].model, SUV[r].price);

        break;

You would do the same for each of the other two categories.

You can similarly bundle the customer info into a single struct, like so, with a pointer to the car information:

struct Customer 
{
    char name[32];
    int age;
    char address[3][32];      /* three lines of 32 chars each */
    struct Car* vehicle;
} customer;

You could then read in the customer information at the beginning of the program, and print it out again at the end along with …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've seen some ludicrous assignments in my day, but this one is among the most absurd I've ever encountered. I would be tempted to walk out on the class if I were handed a project as pointless as this. Still, an assignment is an assignment...

The key to this assignment is to see that the professor wants you to have set the pointers in the first array so that they each point to the matching element in the second array. To do this, you'll need to loop through the pointer array and set each pointer separately:

    for (int i = 0; i < 5; i++)            //assign values of integer array
    {                                      //to integer pointer array
        ptr[i] = &a[i];
    }

Now here comes the part I consider silly. You need to loop through the character array, and set the values pointed to by the elements of the int pointer array (that is to say, the elements of the int array) to the values in the char array.

    for (int i = 0; i < 5; i++)            //assign values of char array
    {                                      //to the pointer array's references
        *ptr[i] = b[i];
    }

Finally, you need to loop through the int array a, and print it's values. This part does nothing in regards to pointers; you just print the values in the a array.

Now, I suppose that the point of this (if there is one) is to demonstrate what happens when you print characters out as …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem is that you are taking the size of the array as the highest index:

    int i = n;
    while (i > 0)
    {
        int pos = positionOfMax(a, i); //find the latest one's position
        rotateLeft(a, i, pos); //move the latest one to the end
        i--;
        pos = 0;
    }

Arrays in C++ are zero-indexed, meaning that for an array of size 6, the indices would be 0, 1, 2, 3, 4, and 5. An index number of 6 will go off the end of the array, causing the segfault. You'll want to change this to

    int i = n - 1;
    while (i >= 0)
    {
        int pos = positionOfMax(a, i); //find the latest one's position
        rotateLeft(a, i, pos); //move the latest one to the end
        i--;
        pos = 0;
    }

Since you seem to make this mistake throughout the code, you'll need to make similar changes across the whole program, I'm afraid.

As for why it doesn't fail in Windows (it should), I'm guessing that it is silently trashing some otherwise unimportant piece of data on main()'s stack area.

BTW, where is myStrlen() declared?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think that if you actually open up the file grade.txt, you'll see that there is no actual line with the text EOF on it; rather, in the example given, the EOF stands in the for the actual end-of-file marker, which isn't a printable character.

In any case, Python provides an easy way to iterate through a text file without using readline() or any explicit test for completion, by using just a for: loop:

inFile = open('grade.txt', 'r')
for line in inFile:
    lst = line.split(',')
    print(lst)
inFile.close()

Another way to do this, which may prove even more useful, is to use the with statement. Let's try that, with a little more formatting to the output as well:

with open('grade.txt', 'r') as inFile:
    for line in inFile:
        lst = line.split(',')
        for element in lst:
            print("{0:<15}".format(element.strip()),  end=' ')
        print()

The major advantage of the with is that you don't need to explicitly close the file.

I could also add that files of this type (called a comma-separated value file or CSV file), are especially common, so much so that Python has a special library just for handling the data from them.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The main problem I see is that you are indexing the arrays incorrectly, which is probably the cause of the segfault. In C++, arrays are zero-indexed, that is to say, an array arr[5] would have elements arr[0], arr[1], arr[2], arr[3], and arr[4]. When you try to access arr[5], you overrun the array and get an access violation.

What this means is that you need to fix all of the array indices in the program. Fortunately for you, I've done just that:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(NULL));

    //Constants
    const double SALESTAX = 0.08;
    const double DISCOUNTRATE = 0.05;
    const double DISCOUNT = 95;

    //Counts
    int customer, book;

    //Customer arrays
    string customer_Non[5][2]; // 1 = name, 2 = address
    int customer_Num[5][2]; // 1 = age, 2 = receipt#
    int quantity = 3; //3 books per customer

    //Book arrays
    string book_Non[5][3][3]; // 1 = book number, 2 = Title, 3 = Author
    int bookAisle[5][3]; // 1 aisle per book
    double bookPrice[5][3][2]; // 1 = book price, 2 = discount

    //Calculations
    double calculation[5][5];
    /* 1 = subtotal, 2= total discount, 3 = subtotal and discount
     * 4 = sales tax, 5 = Total to be paid */

    //Validations
    int customerValid [5][2]; //1 = name validation, 2 = address validation
    int bookValid[5][3][3]; //1 = booknum validation, 2 = title validation,
                            //3 = author validation
    ofstream fOut;
    fOut.open("Project4_A00635756_Output.txt");

    for(customer = 0; customer < 5; customer++)
    {
        customer_Num[customer][1] = rand() % 999 …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the future, when getting this kind of error, please post the traceback and error message as well as he code where it is occurring. I was able to work out the problem this time, but the traceback makes it much easier to figure out the problem once you learn how to read it.

Also, always mention the version of Python you are using; Python 3.x, which is what you seem to be working in, is very different from the older Python 2.x regarding several things, including basic console I/O.

The specific error you are getting is on line 22:

    numPumpkins = input("Enter the number of pumpkins: ")

You are reading in the user input as a string, but - unlike in the code below it on line 29 - you don't convert it to an integer. You need to write it as:

    numPumpkins = int(input("Enter the number of pumpkins: "))

Note that even this isn't foolproof; if the user makes a typing mistake or deliberately enters a value other than an integer, an exception will get raised. To do this properly, you really should wrap the line in a while: loop, and then in a try:...except: block.

    numPumpkins = 0
    while numPumpkins == 0:
        # get the input value separately so you can include it in any error msgs you print out
        numString = input("Enter the number of pumpkins: ") 
        try:
            numPumpkins = int(numString)
        except ValueError:
            print("{0} is not an integer. …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To understand classes, you need to know both the conceptual meaning and their concrete implementation. Abstractly, a class is a description of a type, for example, the class Animal would describe the properties which all animals have. The class acts as a template for creating objects of it's type. A class describes both the state of a given Animal, and the behaviors it is capable of.

A class may have sub-classes; for example, Animal might have the subcategory Carnivore, which in turn might have the subclasses Canine and Feline, and so on down to the particular types of animals such as Lion or Cat. It is possible for a class to be a sub-class of more than one immediate parent class; for example, a Cat is both a Feline (and hence a Carnivore, and hence an Animal), and a Pet (which is a subclass of DomesticatedAnimal, which is a subclass of Animal). Each subclass inherits the properties and behaviors of it's parent classes.

As I said, a class consists of a set of properties (called instance variables) and behaviors (called methods). These properties may in turn be members of a class. For example, a Cat has teeth, claws, and fur. Now, it is important to differentiate here between the type of something and it's properties. A Cat is a Feline (inheritance), for example, but while a Cat has claws (composition), a Cat isn't a type of claw. This may seem obvious, but it can be surprisingly difficult to get this …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just to clarify: the code posted is the mapmaker.py file, while the data is the contents of samos.txt, correct?

It seems to me that the first part of the problem is to figure out how to parse the data. Fortunately, the format seems fairly simple: each item starts with a terrain type, and a (I think) the number of coordinates, followed by a series of x, y coordinates, and separated by empty lines. You should be able to collect the data fairly easily given this.

If you know how to make a class, then I would make one to represent the figures to be drawn, and store the data in your Figure objects. Otherwise, you could use a list consisting of the terrain type, the size, and tuples representing the coordinate pairs.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Yes, please post your existing code for us, otherwise we won't know how to adivse you.

revelator commented: thanks, please do this help for me :) +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In order to get the desired effect for the method getWord(), you will need to make three changes. First, you'll need to track the centerpoint of the circle; a simple list pair would do nicely:

self.center = [200, 200]  # initialize to the original center of the canvas

Then you need to alter moveCircle() so that the changes in the centerpoint are tracked as the circle moves:

    def moveCircle(self, event):
        """move circle up, down, left or right when user clicks an arrow key"""
        x=0
        y=0
        if event.keysym == "Up":
            y = -5
        elif event.keysym == "Down":
            y = 5
        elif event.keysym == "Left":
            x = -5
        else:
            x = 5

        self.canvas.move("circle", x, y)
        self.canvas.move("text", x, y)
        self.center[0] += x
        self.center[1] += y
        self.canvas.update()

Finally, you'll need to change the conditional of in getWords() to calculate the distance between the the current centerpoint and the mouse-down location, and compare it to the radius of the circle:

    def getWords(self, event):
        color = self.getRandomColor()
        self.canvas.delete("text")

        distance = math.sqrt((self.center[0] - event.x) ** 2 + (self.center[1] - event.y) ** 2)
        place = ''

        if distance <= self.radius:
            place = 'inside'
        else:
            place = 'outside'

        self.canvas.create_text(self.center[0],  self.center[1],
                                    text = "Mouse pointer is %s the circle" % place,
                                    fill = color, tag = "text")

This should do the job nicely. Note that I used another instance variable, self.radius, rather than hard-coding the 50 in; this would allow you to change the size of the circle dynamically, later on, and …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Certainly you can nest lists inside another list, and you wouldn't necessarily need another method to do it. If you already have the list to insert, the it is as easy as

>>> alist = [1,2,3]
>>> blist = [4,5,6]
>>> clist = []
>>> clist.append(alist)
>>> clist.append(blist)
>>> clist
[[1, 2, 3], [4, 5, 6]]
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The only processor architecture I know of which has a register file that large is the UltraSPARC, which has (IIRC) 128 64-bit registers (divided into 8 overlapping register windows of 32 registers each).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, no. There are definite limits to computability. Look up Alan Turing and the Halting Problem for one well-known example of an undecidable proposition.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the future, please use the 'code' menu button at the top of the editing window to paste in code samples. By default, the forum software does not retain indentation, which makes reading Python code especially difficult.

As it happens, the causes of the problem are plain to see. First off, you omitted the double-underscores around the __init__() method, which means that it is just an ordinary method of that name, not the constructor as you intended. This is a common enough error, so don't feel too put out about it. The second issue is that you are reading the integer values in using input() function; in Python 2.x, this would work (though it is dangerous because it evaluates the input as a Python statement), but in Python 3.x, the input() function only reads in strings. You will need to convert the strings to integers before passing them to the c'tor. Finally, the values you are passing to the c'tor are the same as the default values; you will want to use the values you've just read in instead. Thus, the code ought to look something like this:

class Rectangle(object):
    """A 2D Rectangle"""

    def __init__(self, width = 1, height = 2):
        self.width = width
        self.height = height

    def Perimeter(self):
        "Return the Perimeter of the rectangle"
        return (2 * self.width) + (2 * self.height)

    def Area(self):
        "Return the area of the rectangle"
        return self.width * self.height

print("Enter your values")

width = 0
height = 0

# read in the input …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, this does clarify things somewhat. OK, then.

I think you'll want to fix calcdist() first; divorce it from the data stream as it is and have it take two three-tuples as it's argument:

def (a, b):
    return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-z[2])**2)

Better still might be to write a Point3D class to represent your data, though that may be a bit heavyweight. On second thought, it would porbably save you a lot of trouble:

from math import sqrt

from sys import maxsize

class Point3D(object):
    """ Representation of a point in three dimensions."""

    def __init__(self,  *args):
        """ C'tor for the Point3D class. Can accept either a tuple, a list, or a set of three separate arguments as it's initialization. """
        if len(args) == 1 and (isinstance(args, tuple) or isinstance(args,  list)):
            self.x,  self.y,  self.z = args[0]
        elif len(args) == 3:
            self.x,  self.y,  self.z = args
        else:
            raise TypeError 

    def __str__(self):
        """ String representation of a Point3D. """
        return "<{0}, {1}, {2}>".format(self.x,  self.y,  self.z)

    def __repr__(self):
        """ Extended representation of the Point3D objects - the same as the string representation."""
        return str(self)

    def __eq__(self,  other):
        """ Test for equality between two Point3D objects."""
        return ((self.x == other.x) and (self.y == other.y) and (self.z == other.z))

    def __ne__(self,  other):
        """ Test for inequality between two Point3D objects."""
        return not self == other    

    def distance(self,  other):
        """ Computes the distance between two Point3D points."""
        return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2 + (self.z - other.z) ** …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I can see your getting flustered, so let's back away from the code for a bit and consider the overall problem you are trying to solve. Just what is the program supposed to compute, and how would you do it by hand if you had to? I don't mean you should actually go through it manually, just sketch out the process for us.

Also, I would recommend removing any import statements that aren't strictly needed. They simply clutter up both the code and the namespace.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The first thing to do is get rid of the existing code in the start.mouseClicked() event handler. Those loops aren't working; you need something that will run each time the Timer event fires. From here on in, all that start.mouseClicked() will do is start the Timer, and all stop.mouseClicked() will do is stop it. The code for resetting the values of msec, sec, and min, and the text of msecs, secs, and mins, will now go in the reset.mouseClicked() event handler.

Next, you need to move the msec, sec, and min integers out to the class level as static variables, while at the same time eliminating the variable flag (you won't need it any more). This allows you to have them changed by the various event listeners.

Next, you will need to declare a Timer, and define an ActionListener for it with a suitable actionPerformed() method. This I'll leave to you, but I want to remind you: don't loop inside the event handler. It will automagically get re-run every tim the Timer event fires. Write your code with that in mind.

As a last piece of advice, replace frame.show(); with frame.setVisible(true);, as show() is deprecated. Just a minor thing to fix.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, are you using a system Date (java.util.Date) or a database Date (java.sql.Date)? I am assuming the former, but if you are working with a SQL database, you may be talking about the latter.

Either way, you will want to use one of the Calendar classes, probably GregorianCalendar. The Calendar classes all support a method called .add() which will do the job you want.

However, when adding or subtracting time from a Calendar object, you need to tell it what incement of time to add - an hour, a day, a year, a month, whichever. so what you would have is something along these lines:

Calendar cal = new GregorianCalendar();   // default is current time and default zone
cal.add(Calendar.DATE, 5);

Note that I haven't addressed the question of time zone, which you may neecd to do.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I believe that what you are looking for is the import statement. If you have a Python file, say test.py, and wish to run the program in that source file while in the interpreter prompt, you can enter

import test

and, provided that the file test.py is in the same directory that you launched the Python interpreter from, you should be able to run the program, as well as access it's variables, call it's functions, etc. once it is imported.

Mind you, this is not the usual manner in which Python programs are run. It is more typical to have the .py files associated with pythonw.exe, which allows you to run the program just by double-clicking on the file. See the link Gribouillis posted for more details.

If, rather, you are looking to edit and test the program in question, you would be better off running IDLE (and simple integrated development environment that should have come with your Python distribution), which has a window for the interpreter prompt but also allows you to open separate editing windows for working on your source files. If you launch IDLE, the go to File-> Open File... and select your test.py file, it will open a window showing the source code; you can then run the program by going to Run-> Run Module in that window. IDLE takes a bit of getting used to, so you might consider a more powerful IDE such as Dr Python (very simple to learn …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What is the expected result?

I suspect that you have misunderstood the last part of the summation formula. I suspect it is supposed to go more like:

         n
       ----
       \         n 
   1 + /     (-1)  n! / (x - n)
       ----
       i = 2

or,

1+2!/((x-2))-3!/((x-3))+4!/((x-4)) - ... n!/((x-n))

which means that for the example given, it would be

1+2!/((x-2))-3!/((x-3))+4!/((x-4))-5!/((x-5))

Note that if n is less than 4, the formula goes shorter than the example given. So, for example, for n = 3, the formula would simply be

1+2!/((x-2))-3!/((x-3))

The practical upshot of this is that you need to compute the sum using a loop.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As per request, one boilerplate answer coming up:

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

And in case you think you won't get caught... think again.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach …

rubberman commented: Loved the thread about "this guy"! :-) +12
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the declaration of struct author, you define down as type link, which is a typedef for struct author*. What you actually want is for it to be a ptr (that is, struct book*). Thus, you'll want to move the typedef of type ptr up to before the definition of struct author, and change link down; to ptr down;.

typedef struct author *link;
typedef struct book *ptr;

struct author
{
       char name[20];
       link next;
       ptr down;
};
typedef link LIST;
typedef link pos_author;


struct book
{
       char title[20];
       int year;
       int page;
       ptr down;
};
typedef ptr pos_book;

Oh, and you misspelled 'title', BTW. HTH.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Rithish: The issue is not in the behavior of the two forms of the function, but rather is in the wording of the C language standard, and less directly, in the behavior of the majority operating system shells. You see, it isn't incidental that main() was type int even in the days of default return values; it was intentional behavior. The return value of the program isn't simply discarded, it is returned to the program which initiated the program run, usually the command shell.The returned value is used as an indicator of the program completion status - 0 means it ran to completion without any fatal errors, any other value indicates that something went wrong. In Unix (and it's descendants, Linux and MacOS X), there is even a standarsd list of error messages one can return, though it is rarely used.

The value isn't always, or even often, used, though it does play an important role in shell script programming, where a half dozen or more different programs may be run by a single script, any of hich could, theoretically, fail.

Also, not every OS uses the value in a meaningful way. Windows doesn't generally do anything with it, though it is capable of it for batch scripting; most embedded systems don't have anything to return to, or else have some less generic method of catching errors.

Prior to 1986 or so, this wasn't a big deal, because it was stadard practice to use a default return value, like this:

deceptikon commented: Nice. +9
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Assuming you are running Windows, the answer is, you don't. DOS TSRs required low-level access to the BIOS, and hooking an interrupt; they are notoriously badly behaved under Windows, even inside of the cosnole or a DOS box.

Under Windows, then the equivalent of a TSR is simply a program that launches without opening a window, and waits for the appropriate invocation. Usually, what you would do is put an icon in the system tray, and wait for it to be clicked to access the program. The 'classic' TSR invocation method of using some specific control-keystroke is discouraged, as it could conflict with other programs which use the same keystrokes.

Can you tell us more about the purpose and goals for this program, and why you want it to behave as a TSR?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What it comes down to is that each state transition can have it's own behavior, represented by a function. In this case, all of the states use the same function to handle the different states, but that is just to keep the code simpler; in practice, you would probably have one function for each state transition.

You may want to compare this to another FSM design which I came up with for a compiler class some years ago. It is also in Python, and while the two have some striking similarities, they also have significant differences as well.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To answer to OP's question, the exact use of bit fields is to allow you to pack several small values into a single integer value, by defining the values in terms of how many bits they need in order to be stored efficiently. As Deceptikon said, they are primarily useful for things like flags, which take only one bit each, or for small integer values.

The main downside to bitfields is that the exact order in which the bits are stored is compiler-dependent, as are other related issues such as the size of an int value. This means that some of the most desireable uses of them - representing the fields of an I/O port, for example - aren't portable. Now, this may actually be less of an issue than it sounds, since most of these uses are system-dependent anyway, but it does mean that anything that isn't system-specific cannot use bitfields without losing portability.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The shell command you are looking for is g++ filename -o executablename, or at least that will get you started (the '-o' stands for 'output', and let's you choose the name of the final executable). Look up the documentation on GCC and make for more involved compilation.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, fixated on the first part as I was, I missed the whole question. Ah, yes, here's the problem: you are putting the numbers in quotes, which means that you are comparing the input values (0, 1, 2, 3) against their character representations ('0', '1', '2', '3'). While those representations are indeed treated as valid int values, they are not the same values as the integers. For example, the character '0' is actually encoded as the numeric value 48. Thus, you want to drop the quotes around the numbers, like so:

int printOutcome(int choice, int compChoice)
{
    if (choice == 0 && compChoice == 0)
        cout << "Tie \n";
    if (choice == 0 && compChoice == 1)
        cout << "Computer wins\n";
    if (choice == 0 && compChoice == 2)
        cout << "Human wins\n";
    if (choice == 1 && compChoice == 0)
        cout << "Human wins\n";
    if (choice == 1 && compChoice == 1)
        cout << "Tie\n";
    if (choice == 1 && compChoice == 2)
        cout << "Computer wins\n";
    if (choice == 2 && compChoice == 0)
        cout << "Computer wins\n";
    if (choice == 2 && compChoice == 1)
        cout << "Human wins\n";
    if (choice == 2 && compChoice == 2)
        cout << "Tie\n";
    cout << endl;
}

This has the values compared to the equivalent integer values, not the character encodings.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You could eliminate a certain amount of redundancy by using toupper() (defined in the <cctype> header) to force the user input to upper case:

int userChoice()
{
    char choice;
    int choice2;
    do
    {
        cout << "Please enter your choice[r,p,s,q]: ";
        cin >> choice;
        choice = toupper(choice);
        cout << "Human: " << choice;
    }while ((choice != 'R')&&(choice != 'P')&&(choice != 'S'));

    if(choice == 'R')
        choice2 = 0;
    if(choice == 'P')
        choice2 = 1;
    if (choice == 'S')
        choice2 = 2;
    if (choice == 'Q')
        choice2 = 3;

    return choice2;
}

It's a small change, but one which makes the function quite a bit easier to read.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've run across this before, and the short answer is: you can't.

DLLs were designed originally with the Pascal language in mind, and as a result, older 16-bit DLLs often used the Pascal parameter passing conventions. By the time Win32 came on the scene, Pascal was largely forgotten, but, Visual Basic was on the rise inside of Microsoft, so a new calling convention, __stdcall, was developed for language-indpendent parameter passing. This became the standard for pretty much all modern DLLs.

One thing that was not supported was classes. Object models of different languages were too different, and for system programming Microsoft assumed you'd be using C in any case. Full support for object-oriented programming didn't come around until .NET, and then only for .NET style objects and classes.

The practical upshot of this is that while you can have a class inside of a DLL, you have to 'unwrap' the class by providing external functions which act as an intermediary to the class's methods.

Lucaci Andrew commented: Indeed. +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First, permit me to re-post the code with suitable indentation, courtesy of Astyle:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include "windows.h"

using std::cout;
using std::endl;

bool ListDirectoryContents(const char *sDir)
{
    WIN32_FIND_DATA fdFile = {0};
    HANDLE hFind = NULL;
    ULONGLONG fileSize;
    time_t rawtime;
    struct tm * timeinfo2;
    long bsize;
    float kbsize;
    char sPath[2048];
    sprintf(sPath, "%s\\*.*", sDir);
    if ((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
    {
        printf("Path not found: [%s]\n", sDir);
        return false;
    }
    do
    {
        if (strcmp(fdFile.cFileName, ".") != 0 && strcmp(fdFile.cFileName, "..") != 0)
        {
            sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);
            if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                ListDirectoryContents(sPath);
            }
            else
            {
                cout << "# FILE NAME: ######################################################" << endl;
                cout << "File: " << sPath << endl;
                cout << "# FILE SIZE INFO: #################################################" << endl;
                bsize = fdFile.nFileSizeLow;
                kbsize = (float) bsize / 1024;
                cout << "SIZE: " << fdFile.cFileName << " " << bsize << " bytes " << kbsize << " kb" << endl;
                cout << "size HIGH: " << (fdFile.nFileSizeHigh * (MAXDWORD + 1)) + fdFile.nFileSizeLow << endl;
                fileSize = fdFile.nFileSizeHigh;
                fileSize <<= sizeof ( fdFile.nFileSizeHigh) * 8;
                fileSize |= fdFile.nFileSizeLow;
                cout << "fileSize: " << (DWORD) fileSize << endl;
                cout << "# FILE ACCESS INFO: ################################################" << endl;
                time((time_t*) & fdFile.ftLastAccessTime);
                cout << " --> last open: " << ctime((const time_t*) &fdFile.ftLastAccessTime) << endl;
            }
        }
    }
    while (FindNextFile(hFind, &fdFile));
    FindClose(hFind);
    return true;
}

int main()
{
    ListDirectoryContents("C:\\Repository_Files\\");
    return 0;
}

Now, when I compile and run this (under Code::Blocks, with MinGW GCC …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Finding a favorite language is a bit of a personal experience, so it's hard to give exact advice. While a part of me still wants to plump for Scheme (and specifically Structure and Interpretation of Computer Programs, a classic introductory textbook that is available online), I have to second the suggestion of trying Python. It is a very simple yet powerful language with a straightforward syntax that doesn't get in the newcomers' way.

The only caveat I would make is to be careful about which version of the language you choose. There are significant differences from version 2 to version 3, and the two different branches of the language are (for the time being) maintained independently of one another. While version 3.3 (the latest 3.x release at this time) is the one I would recommend, there are a lot of tools and libraries that only work with version 2.7 or earlier, and if you need to use a specific toolset, you may find yourself in the position of having to use the older revision of the language.

The main Python website has some excellent tutorials to start with, as well as extensive documentation on the language. As for textbooks, I, too, have heard of Learn Python the Hard Way, but I haven't looked into it enough to say if it is a good choice or not. One textbook I can recommend is Think Python, an updated version of the venerable …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Mainly, that it leverages the existing EnumMap class rather than having to write a c'tor and accessors for the Rank class. Also, because it decouples the value of the cards from the Rank class, it makes easier to re-use the classes for another type of card game (e.g., poker, bridge). While neither of these is a big deal in this particular case, they are good design practices to get familiar with.

speakon commented: Thanks! +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As it happens, there is a class named EnumMap which is designed for precisely this situation. It provides a mapping keyed to an enumeration. I this case, you would use it something like this in the class BlackJack:

static final EnumMap<Rank, int> rank_value = new EnumMap<Rank, int>(Rank);

static {
    rank_value.put(Rank.Deuce, 2);
    rank_value.put(Rank.Three, 3);
    rank_value.put(Rank.Four, 4);
    rank_value.put(Rank.Five, 5);
    rank_value.put(Rank.Six, 6);
    rank_value.put(Rank.Seven, 7);
    rank_value.put(Rank.Eight, 8);
    rank_value.put(Rank.Nine, 9);
    rank_value.put(Rank.Ten, 10);
    rank_value.put(Rank.Jack, 10);
    rank_value.put(Rank.Queen, 10);
    rank_value.put(Rank.King, 10);
    rank_value.put(Rank.Ace, 11);
};

You could then use this to get the values of the cards:

    /*
    * Print Initial Cards
    */
    System.out.print("The Dealer Has: " + deck.dealer.getDealerList() + " for a total of ");
    int dv = 0;
    for (Card card : deck.dealer.getDealerList()) {
        dv += rank_value.get(card.getRank());
    }
    System.out.println(dv);

    System.out.print("You Have: " + deck.user.getUserList()  + " for a total of ");
    int pv = 0;
    for (Card card : deck.user.getUserList()) {
        pv += rank_value.get(card.getRank());
    }
    System.out.println(pv); 

I hope it is clear how this works.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The deck instance variable probably should be an ArrayList<Card> rather than ArrayList<String>.

I would make the suits and values of the card enumeration types, rather than strings; that way, you can change the representation (using abbreviations, for example, or images of some kind), without needing to change the Card or Deck classes themselves. This sort of decoupling of the user interface with the logic is often a valuable approach.

enum Suit {Hearts, Clubs, Diamonds, Spades};

enum Face {Ace, Deuce, Trey, Four, Five, 
           Six, Seven, Eight, Nine, Ten,
           Jack, Queen, King};

public class Card {

    private Suit suit;
    private Face value;

    public Card(Face v, Suit s) {
        value = v;
        suit = s;
    }

    public String getValue() {
        return value;
    }

    public String getSuit() {
     return suit;
    }
}

Fortunately, Java enumerations are a lot more flexible than those in C or C++, and you can extract the string form of an enumerated value just by using either name() or ToString(). Thus, while you can decouple the interface if you choose, you can also 'cheat' a bit and use the actual enumerated values.

You probably want to write one or more comparison methods for the Card class.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You don't necessarily want to hard-code the size of the Deck, either. The reasons for this are four-fold:

  • As the play goes on, the size of the Deck will decrease, until it reaches the point where you need to reshuffle the discards, at which point it will go back to the original size,
  • You may want to extend your deck with additional Cards (e.g., jokers),
  • You may want a 'shoe' of cards consisting of more than one 52-card deck (as is done in most casinos), and
  • The easiest way to handle the player's hand is to sub-class Deck, in which case the size will always be smaller than 52.

Just some advice based on my own experience implementing a card game.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend using a color picker control rather than a combobox, if only for the compactness of the design.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh, sorry; I should have provided more information. The Java HashMap generic class is a standard Collection that behaves as a dictionary or lookup table (sometimes also called an associative array or associative map). It provides a mapping between two values.

When you create the HashMap, you give it two types, one for the key and the other for the value. You add key-value pairs to the HashMap to make the table. You can then use a key to look up a value in the HashMap.

As for why they are superior to an ArrayList, they aren't; they are used in a completely different way from an ArrayList with very little overlap. What they are superior to in this case is the long sequence of if() statements which you were using to determine the values for the cards. Not only is it more compact, you can use it in mutiple locations with very little code. It is an approach known as data-directed programming, where you use the structure of the objects to provide the solution to a problem rather than relying on code for it.

Oh, I noticed a few errors in my earlier code; notably, I used == where I should have used .equals(), and forgot to pass card to the .get() method of the HashMap.

     if (card.equals("Ace")) {
          if (dValue <= 10) {
              dValue += 11;
          }
          else {
              dValue += 1;
          }
      }
      else {
          dValue += faceValues.get(card);
      }

HTH.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The simple answer for why b is not defined in this loop:

while b <= 10:
    print (b)
b += 1

is that b is not, in fact, defined, at least not when you are trying to compare it to 10. Thus, you do indeed want to initialize it to zero before the beginning of the loop.

But wait, you say, why then is it causing an infinite loop, when you clearly have an increment in the loop? Well, the answer there is, you don't have an increment in the loop; you have an increment after the loop, where it does you no good at all. This is simply a matter of incorrect indentation, and easily is solved thusly:

b = 0
while b <= 10:
    print (b)
    b += 1

To finish up, let me answer a question which you haven't asked: why doesn't the while: loop's conditional value default to zero, when the equivalent for: loop's is:

for b in range(0, 11):
    print (b)

The answer is that the value of this b is getting set by the range() generator on the first pass of the loop, and is reset on each subsequent pass.

Lucaci Andrew commented: Nicely done +4
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

On the card values, I would recommend using a HashMap as a reverse lookup table for the card face values. Something like this should do:

private HashMap<String, int> faceValues = new HashMap<String, int>(20);

faceValues.put("Ace", 1);
faceValues.put.("Deuce", 2);
faceValues.put("Trey", 3);
// handle all the numbered cards
for (int i = 4; i <= 10; i++) {
    faceValues.put(Int.toString(i), i);
}
faceValues.put("Jack", 10);
faceValues.put("Queen", 10);
faceValues.put(King", 10);

You'll need some additional logic for handling the case where Ace is treated as 11, but beyond that, this should make looking up the card values much easier.

 /*
  * Dealers Cards Value
  */
 public int getDealersValue(int dValue) {
     dValue = 0;
     for(int i = 0; i < dealersCards.size(); i++) {
         String card = dealersCards.get(i);
         if (card == "Ace") {
             if (dValue <= 10) {
                 dValue += 11;
             }
             else {
                 dValue += 1;
             }
         }
         else {
             dValue += faceValues.get();
         }   
     }

     dealersValue = dValue;
     return dValue;
 }

The same would be done with the user's cards, except that the user would have to be queried abuot how to treat the aces.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There is another approach to this, which would not require you to rebuild the list; however, the technique needed is not that different from that used to reverse the list, so which would be the most useful would depend on the overall goal. In essence, what you would do is recurse down the length of the list, then apply the operation you need to perform on the list:

struct Node 
{
    int data;
    struct Node* next;
};

void printReverse(struct Node* list)
{
    if (list == NULL)
        return;
    else
    {
        printReverse(list->next);
        printf("%d ", data);
    }
}

This is jut a quick-and-dirty example; you'd need to apply the technique as appropriate.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That depends, I would say, on how you mean to use the two methods. Personally, I would probably have only one form of the method, one which takes an istream& as it's argument; this covers both the case of a file input (ifstream&) and string input (istringstream&), and gives you additional options besides (e.g., reading from std::cin for a filter).

I would add that you may want to have it return a vector of an abstract Token class, rather than of plain std::strings. This would allow you to specialize the set of tokens a given Lexical object returns with additional information aside from the contents of the string itself.

Or perhaps you could combine the two sets of ideas, and have it return a stream of Tokens? You'd need to define a tokenstream class, as an extended form of an ios, and then... hmmn, let me think this out a bit.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, stop using the SMS abbreviations; no one will take you seriously here if you insist on that sort of thing. Write out clear, complete English sentences, to the best of your ability, please.

Second, while I know it is a picayune point to make, void main() is not valid in a portable C program; the older standard allowed it, but the only really correct form is int main().

On a related note, drop the #include <conio.h> directive - <conio.h> is not a standard header, and you don't use any functions from it in any case.

Finally, never, ever use gets() - it is too dangerous, because it is unbounded and can overrun the buffer you are reading the data into. Please use fgets() in the future.

That having been said: what is the program actually doing, and how is it failing? As it is right now, my C compiler gives three warnings when I compiler the code:

Compiling: C:\Users\Jay\Documents\Programming\postfix.c
C:\Users\Jay\Documents\Programming\postfix.c: In function 'to_postfix':
C:\Users\Jay\Documents\Programming\postfix.c:22:19: warning: comparison between pointer and integer [enabled by default]
C:\Users\Jay\Documents\Programming\postfix.c:54:15: warning: assignment makes integer from pointer without a cast [enabled by default]
C:\Users\Jay\Documents\Programming\postfix.c:55:5: warning: function returns address of local variable [enabled by default]
Linking console executable: C:\Users\Jay\Documents\Programming\postfix.exe
Process terminated with status 0 (0 minutes, 0 seconds)
0 errors, 3 warnings

The last one I suspect is the critical one - you are passing the back the value of postfix, but postfix is a local variable of to_postfix(), which means it won't have …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, let's start over with new variable names, just to make it clearer, and add some test prints to show what is happening at each stage. I did this and was able to get the program working, in fact:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int iterations, initial_tax_years, increased_tax_years, product_tax, total_years;
    int i, j, k;
    long int* total_tax;
    long int *annual_tax;

    printf("How many iterations to test: ");
    scanf("%d",&iterations);
    total_tax = (long int) calloc(iterations, sizeof(long int));

    for(i = 0; i < iterations; i++)
    {
        printf("How many years for the first tax increase period: ");
        scanf("%d",&initial_tax_years);
        printf("How many years for the second tax increase period: ");
        scanf("%d",&increased_tax_years);
        printf("How many years for the final tax increase period: ");
        scanf("%d",&product_tax);
        printf("How many total years to review: ");
        scanf("%d",&total_years);
        annual_tax = (long int*)calloc(total_years, sizeof(long int));
        printf("How much was the initial tax payment: ");
        scanf("%ld", &annual_tax[0]);

        /* print out the initial state */
        printf("\n\nyear 0 == %d\n", annual_tax[0]);

        for(j = 1; j <= initial_tax_years; j++)
        {
            annual_tax[j] = annual_tax[j - 1] + 1;
            printf("year %d == %d\n", j, annual_tax[j]);
        }
            annual_tax[j] = annual_tax[j - 1] + 1;

        for(j = initial_tax_years + 1; j <= (initial_tax_years + increased_tax_years); j++)
        {
            annual_tax[j] = annual_tax[j - 1] * 2;
            printf("year %d == %d\n", j, annual_tax[j]);
        }

        for(j = (initial_tax_years + increased_tax_years + 1); j < total_years; j++)
        {
            annual_tax[j] = 1;

            for(k = 1; k <= product_tax; k++)
            {
                annual_tax[j] = annual_tax[j] * (annual_tax[j - k]);
            }

            printf("year %d == %d\n", j, annual_tax[j]);
        }

        total_tax[i] = annual_tax[total_years - 1] …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend starting off with the representation of the deck of cards. Have you studied classes and object-oriented programming yet? If you have, then the easy thing to do is create a class Card, which can have one of the 52 face and suit values, then use that to create a Deck class. You can even subclass Deck to make a Hand class (or at least, that was how I did it when I was writing my old Acey-Deucy simulation - it's just too bad that I don't have a copy of it on hand for you :p I think I may have posted it somewhere, though, so hint hint perhaps a search would help...).

Once you have a simulation of the card decks, you can simply write the game by applying the scoring rules to each hand.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think I see the problem here; you are making an understandable but incorrect assumption about how arrays work in C. In C, arrays do not start with the element one, but rather with element zero. Conversely, the last element of an array is not the size of the array, but the size of the array minus one. To put it another way, the elements of an array declared int a[4]; would be a[0], a[1], a[2], and a[3]. There is no a[4] in a four-element array in C; the 4 in the declaration is the size of the array, not the index of the last element.

Thus, the correct way to walk through an array is

int i;
int a[10];
for(i = 0; i < 10; i++)
{
    // do something here
}

There are good, if somewhat obscure, technical and mathematical reasons for zero-indexed arrays; this blog article covers one line of reasoning on the subject, and the Wikipedia article on Zero-Based Numbering gives an overview of a few more. Suffice it to say that, except for a few older languages, almost all programming languages use zero-indexed arrays, for better or for worse.

As for the compiler, you might find Visual C++ Express easier to use than CFree, I'm not sure. However, since CFree will work with the newest version of MinGW, the easier solution is to download and install MinGW, then set CFree to use the newer version …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To address the last question first, it depends on which compiler you're using, and wether it is configured to catch all of these given issues. I have my compiler set to warn me about a lot of things which aren't, strictly speaking, errors in C, but which are nonetheless causes of bugs. Even with that, however, it didn't catch the problem with not having n initialized; I noticed it myself, when going through the code. As for the header issue, what it actually warned me of was that calloc() was not declared before use, and that the return value did not match the default; it took a bit of experience and familiarity with the standard library to recognize the cause of the problem.

Speaking of compiler differences: when I compile and run the code as given, I get a segfault. I tracked this down to the last of the for() loops, where you have the conditionals in the form

    for(l = (s1+s2); l<=n; l++)
    {
        ptr[l]=1;
        for(m=1; m < k; m++)
            ptr[l]=ptr[l]*(ptr[l-m]);
    }

The problem is that l (a very bad variable name, BTW - it can too easily be confused with 1 when reading the code) is being tested as less than or equal to n, which means that on the last loop, l equals n. This is a problem, because the indices of the array only go from 0 to n - 1. Thus, you are walking off the end of the array during the …