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

Setting the overall goal aside for the time being, what it sounds like is that you want help in processing command-line arguments. While the details of this can be rather tricky, the basics are fairly straightforward.

In C and C++, command-line arguments are passed to the program as a pair of optional parameters for the main() function. These parameters are an int value and an array of array of char. By convention, these are named argc (for 'argument count') and argv (for 'argument values'). The full function header of main() thus becomes:

int main(int argc, char* argv[])

Generally, you would start by checking the value of argc to see if any arguments were passed, and if so, how many. You would then check the values in the individual sub-arrays of argvto get the actual arguments. By convention, under most systems, the zeroth argument is the path of the executable program itself.

To give a simple example, here is a simple program that echos the arguments to stdout:

#include <iostream>
#include <cstdlib>

int main(int argc, char* argv[])
{
    if (argc < 1)
    {
        std::cerr << argv[0] << ": no arguments passed" << endl;
        exit(-1);
    }
    else 
    {
        for (int i = 1; i <= argc; i++)
        {
            std::cout << argv[i];    
        }
    }    
    return 0;
}

Now, this doesn't really process the arguments much; it accepts no flags or switches, and doesn't actually use the values of the arguments other than to repeat them back out. …

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

We can help you debug the program, certainly. We won't 'help' you by doing it for you.

The code as given is far from a working program; the most obvious problem with is the inconsistent use of capitalization, which in a case-sensitive language is an error. That is to say, the identifier cin is not the same as Cin, which is not the same as CIN or CiN or CIn. This is especially important with keywords in the language such as int, none of which should ever be capitalized.

As an aside, it is generally not a good idea to write code in a conventional word processor such as MS Word; they not only use a file format that is significantly different from the plain ASCII that the compiler needs, they tend to use some non-standard character such as the so-called 'smart quotes', which will not be recognized by the compiler.

Furthermore, your code isn't formatted. While this won't prevent the code from working, it will make it damn-near unreadable to the majority of C++ programmers. Thus, to fix these issues, you would want to re-write you code thusly:

int readMarks (int ID [5], int TAB[5])
{
    int i, idnum, mark;
    bool stop=false;
    i=0;
    while(!stop && i < 5)
    {
        cout << "enter an ID number to stop give negative value"<<endl;
        cin  >> idnum;
        if (idnum<0)
            stop=true;
        else
        {
            do
            {
                cout<<"enter number of correct answers"<<endl;
                cin>>mark;
            } 
            while(mark<0||10);
            ID [i]=idnum;
            TAB[i]=mark;
            i++;
        }
        if (int grade)
        {
            int …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Not exacty. What the Rxx registers are are the 64-bit versions of those registers, which supercede - and incorporate - the 32-bit Exx registers. By this I mean that the register EAX, for example, still exists, but it is now a sub-section of the RAX register, just as the 16-bit AX register is a part of the EAX regsiter (and the RAX as well). The lower half of the RAX register is the EAX register, while the lower half of EAX is AX; the two halves of AX are in turn AH and AL. This posting goes into additional detail, and may help you understand things better.

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

The MOV instruction is for moving (copying, actually) a value from one memory location to another (or from memory to a fast register, which is sort of special kind of memory for performing operations in quickly and for holding special values the system needs to keep track of, or vice versa). The first argument is the destination, while the second is the source. So, for example, the line mov ebp, esp copies the value in the ESP register to the EBP register. Similarly, the statement mov eax, ds:atexit copies the value in the memory location labelled atexit in the data segment (ds) to the EAX register.

The SUB instruction subtracts the value in the second argument from the first, and puts the result in the first argument location. Thus, sub esp, 8 reduces the value in the ESP register by 8.

The PUSH instruction will take a bit more explanation. As I've mentioned, EBP, ESP, and EAX are registers; specifically, the 32-bit forms of the base (or frame) pointer, the stack pointer, and the accumulator (general-purpose) register. The value in EAX will depend on the program, but EBP should hold a pointer to a location in the middle of the system stack (more on this in a moment), while ESP holds the current top of the stack.

So, what is the stack, anyway? It is a region of memory which is set aside for temporary values, which are organized as a last-in, first-out data structure, conceptually resembling a …

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

I'm not sure what to say here, to be honest. While I don't see anything outright badly done, I don't feel very comfortable about some aspects of it, but I'm having some trouble pinning down just why. The way you mix UI and game logic elements is very uncomfortable to me, but not really wrong per se; I'm not certain how to advise you on improving it. The whole things seems vaguely off, as if there were some underlying misuse of the class system going on that is nonetheless entirely acceptable from a practical standpoint.

I wish I could be more specific about this, but there's just something vaguely inaesthetic about it to me.

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

That, unfortunately, is one thing we won't do for you here; you have to write the program on your own, we'll help you debug it but we won't write it for you

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

I think you've missed WaltP's point, which was that the counts for each upper and lower case value could simply be added together after the fact.

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

On a casual scan, I see that the section where you test for the input value being a letter can be simplified by using the isalpha() function (actually, it's usually implemented as a macro, but that's besides the point).

while (isalpha(inpLetter));

On a related note, the toupper() and tolower() functions can be used to simplify any case where you are accepting either an upper or lower case value as the same.
I'll look over it a little more carefully to see if I can suggest anything else.

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

First, as a minor point that you should be aware of, you should never use void as the return type of the main() function. While earlier versions of the C standard allowed it, it is non-portable; in C++, it is strictly forbidden. Use int main() in the future, please.

Also, please make sure your code is suitably indented to make reading easier. While the formatting conventions may make the code look like some sort of weird poetry, they make the code far easier to read, and with practice become quite natural.

As for how you would allow for multiple users' PINs, the answer lies with arrays, and a loop on the test for whether the PIN matches or not. If you have covered arrays at all yet, this should become clear with a little thought.

I would add that it would make far more sense to use a 4-character array for the PIN, and a test to make sure that the input is numeric (using the function isdigit() from the <cctype> library). The reason for this should become apparent if you consider the case of PINs starting with a zero ('0') character.

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

How is it getting corrupted? Just what is the problem behavior?

Now, I should mention that the way you have the for() loops indexed is potentially problematic, because you are starting at 10 on each of them. Why would this be a problem? Because a ten-element array would have indices from 0 to 9, not 0 to 10. The result is that, from the very start, you are walking off of the end of the array. If you change the initialization so that it begins at 9, rather than 10 - or better still use a named constant - you should avoid this problem.

const int SCORE_COUNT = 10;

int main()
{
    string names[SCORE_COUNT];
    int score[SCORE_COUNT];

    for(int scores = SCORE_COUNT - 1; scores >= 0; scores--)
    {
        cout << "What is your score? ";
        cin >> score[scores];
        cout << endl;
    }

Of course, it would be more conventional to do it like this:

    for(int scores = 0; scores > SCORE_COUNT; scores++)
    {
        cout << "What is your score? ";
        cin >> score[scores];
        cout << endl;
    }

but I gather you have some particular need for the scores to be stored in reverse order.

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

Eh? It was already true when I started learning programming, back in the mid-1980s. I've only known two instructors to use them: one was a high school gym teacher who had been enlisted into teaching AppleSoft BASIC some time around 1984, while the other was (and presumably still is) a tenured professor who seemed to make his mission to make C++ as much like FORTRAN IV as humanly possible. I have never seen flowcharts in use in any other courses, nor from any textbook written after the Carter administration.

While flowcharts fit unstructured languages like Fortran and older forms of BASIC, they make for at best an awkward fit for anything that is block structured, and in particular, they don't represent while loops very well at all (they tend to come out as tail test - that is, do/while - rather than while), and they tend to break down when describing recursive processes. However, even in courses teaching unstructured languages (e.g., assembly), flowcharts are mostly forgotten.

As for what replaced them, they weren't so much replaced as simply abandoned, as far as I can tell, along with HIPO charts, railroad diagrams, and most other diagramming methods. Most students I've known don't use any sort of visual representation of code until they start into OO design, at which point they get UML (and damn little by way of explanation); that, plus FMA diagrams if they take a compiler course, are pretty much it these days, AFAICT.

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

Unfortunately, this approach wouldn't work in any case, at least not in any consistent manner; this is because the integer component of the structure will, in many cases, have an offset to force it to align to a word boundary. This is a system-dependent and compiler-dependent behavior, and would cause the subsequent read() to fail as it would not know how large the alignment padding is.

What you really need to do is serialize the structure, that is to say, which is to say (in this case), you need to save the individual components separately. You may find it easier to do this in discrete functions rather than inside the main() function, just for modularity's sake:

const BUFFER_SIZE = 1024;

void writeInfo(std::fstream& fs, const Info& person)
{
    fs.write(person.name.c_str(), person.name.length() + 1);
    fs.write(reinterpret_cast<char *>(&person.age), sizeof(int));
}

void readInfo(std::fstream& fs, Info& person)
{
    char buffer[BUFFER_SIZE];
    char* p;
    int age;

    fs.read(buffer, BUFFER_SIZE - 1);
    buffer[BUFFER_SIZE - 1] = '\0';     // force-delimit the input
    person.name = buffer;

    p = buffer;
    while (*p != '\0')  // seek to the end of the name string
        p++;

    fs.seekg((p - buffer + 1), ios::cur);  // set the getpos to the integer value
    fs.read(reinterpret_cast<char *>(&age), sizeof(int));
    person.age = age;
}

Mind you, it may make sense to use a text value for the integer, here, as well; this would allow you to view the data in a standard text editor.

mike_2000_17 commented: nice keep it up! +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What sort of problem is occurring? Is it not compiling (it shouldn't, as I'll expain below)? Is it compiling but crashing? Is it giving the wrong results? Can you explain the problem that is occurring?

I do see at least one show-stopper, in that you aren't declaring the variable z in the function multiple(). That by itself should prevent the program from compiling.

Also, I think you'll find that you want to reverse the modulo operation; as it is now, it would return 1 if x is a multiple of y, rather than the other way around.

BTW, is this program supposed to be in C++, or in C? I ask this because the code is C code (modulo the C++-style comments), and while it should compile under C++ as well, it does not take advantage of any of the C++ methods, and uses the older C-style headers.

As a final bit, you could simplify this function by a bit of a trick:

int multiple(int x, int y)
{
    return !(y % x);   // returns 1 if zero, 0 otherwise
}

This works because, in C and C++, any integer value other than 0 is treated as true.

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

OK, so we now know what the program you're working on is supposed to do. What problem are you having with it? Do you know how to write the function, and how to use it once it is written? Are you stuck on some part of it?

You must understand, we will not write this program for you. We are here to help you learn, not to help you cheat. While that may not be your intention, just dumping the problem statement on us comes across as a demand to do your work for you, and that is simply not going to happen.

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

I have to agree with WaltP; if you are writing a simple program that resembles a language interpreter, and it is capable of computing non-trivial equations of more than a fixed size, then you really are talking about writing an intepreter. You'll want to go the whole route of tokenizing and parsing the input, even if the input is supposed to be limited in scope.

I suggest you start out with a simple, ad-hoc tokenizer, something that can break a line of input into a series of discrete elements that can then be operated upon by an equally simple parser. Something like this should be a good start:

enum TOKEN_TYPE {TK_ERROR, TK_INTEGER, TK_PLUS, TK_MINUS, TK_MULT, TK_DIV, TK_PRINT, TK_IDENTIFIER};

struct Token 
{
   std::string value;
   TOKEN_TYPE type;
};

Token* get_next_token(std::istream& source) 
{
   char next_char;
   next_char = toupper(source.get());

   if (isalpha(next_char))
   {
       Token* id = get_identifier(source, next_char);
       if (id->value == "PRINT")
       {
           id->type = TK_PRINT;
       }

       return id;
   }
   else if (isnumeric(next_char))
   {
       return get_integer(source, next_char);
   }
   else
   {
       Token* op;
       op = new Token();
       op->value = next_char; 
       switch(next_char)
       {
        case '+':
            op->type = TK_PLUS;
            break;
        case '-':
            op->type = TK_MINUS;
            break;
        case '*':
            op->type = TK_MULT;
            break;
        case '/':
            op->type = TK_DIV;
            break;          
       }

       return op;
    }
}

Token* get_identifier(std::istream& source, char start_char)
{
    Token* id = new Token();

    id->value = start_char;

    while(true)
    {
        char next_char = toupper(source.get());

        if (isalphanum(next_char))
        {
            id->value += next_char;  // append the current char to the value string
        }
        else 
        {
            source.putback(next_char);
            break; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, it would have made much more sense to attach the files to the message itself (using the Files menu item in the Daniweb editor window), rather than expect others to go to a different site - one which requires a log in - and download a compressed file, sight unseen. Just something to take note of.

Second, you don't really say what you want us to do to help you. This kind of open-ended question rarely gets a satisfactory answer here, simply because it's hard to tell what you really are looking for yourself. If you could be a bit more explicit, we'd be able to help a lot more effectively.

Third, what does this code have to do with C++? The psuedo-code doesn't particularly resemble C++ (or any other modern language), and you don't say whether the intent is to translate it into C++ later or what have you. Could you tell us some more about your goals with this project?

Finally, a lot of the younger members are probably unfamiliar with flowcharts; they are generally considered obsolete, as they are too low level to reflect modern program structure. If this is for a class assignment, then you don't have much choice, to be sure; OTOH, and IMAO, a professor who still uses flowcharts in this day and age probably ought to be enjoying their retirement rather than foisting these questionable tools on a new generation of programmers. For the most part, flowcharts aren't likely to help …

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

I agree with marh; from the look of it, the line should read

        currentPtr = currentPtr -> Next;

A few other comments:

  • Is this C++ code, or C code? While this code should work under most C++ compilers, the languages are not at all the same. This seems to be C rather than C++; for example, you use only the C-style I/O functions, and the headers (<stdlib.h> etc.) you are using are the C style headers, as opposed to the newer C++ headers (<cstdlib> and so forth). Likewise, the declarations of the structure variables are C-style; in C++, you don't need to explicitly have the struct keyword in the variable declarations.

  • What compiler and operating system are you writing this for? If this is meant to be C++, you may be using a much older compiler, which would explain some of what was noted above.

  • You should never use void main(); while the older C standard allows it on non-standard systems (embedded OSes and the like, where there may not be a shell to return to), it is considered non-standard and isn't portable. It is not allowable in C++, and the latest C standard eliminates it IIRC. Unless the specific platform you are on requires something different, you should always use int main() in both C and C++.

I hope this helps.

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

As the other posters say, you haven't explained what problems you are having. We can't do much without more information, I am afraid.

I will make a comment, however: with the current version, you are hard-coding a lot of details which could, and probably should, be broken into more general methods. For example, you have the following code, which essentially repeats the same operation:

    print "Warrior info:"
    print "\tPower: %s" % warrior.power
    print "\tAttack: %s" % warrior.attack
    print "\tDefense: %s" % warrior.defense
    print "\tAttacks: sword, crossbow, knife"
    print
    print "Wizard info:"
    print "\tPower: %s" % wizard.power
    print "\tAttack: %s" % wizard.attack
    print "\tDefense: %s" % wizard.defense
    # ... further down ...
    print "Orc info:"
    print "\tPower: %s" % Orc.power
    print "\tAttack: %s" % Orc.attack
    print "\tDefense: %s" % Orc.defense
    print
    print "Troll info:"
    print "\tPower: %s" % Troll.power
    print "\tAttack: %s" % Troll.attack
    print "\tDefense: %s" % Troll.defense
    print
    print "Dog info:"
    print "\tPower: %s" % Dog.power
    print "\tAttack: %s" % Dog.attack
    print "\tDefense: %s" % Dog.defense

As a rule, it would make more sense to have a common function or method which would perform this operation, preferably once and only once. It could even apply to both the 'player characters' and the 'creatures', if you have a parent class which both inherit from.

    class Creature (object):
        def __init__(self, name, power, attack, defense):
            self.name = name
            self.power = power
            self.attack = attack
            self.defense = defense

        def stats(self):
            print ("%s's info:" % self.name)
            print …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I assume you are using the system() function to call the C programs. This is the simplest approach, but as you can see, it is rather limited.

As it happens, PHP has another built-in function for this purpose, called exec(). It returns an array of strings which contains the standard output stream (STDOUT) of the C program; in this regard, it is somewhat similar to using a pipe (though pipes don't break up the stream into lines). All you need to do is have the C program printf() the desired values, and you can get the result when the C program returns.

If you need a binary value, however, you might want to use passthru() instead, which is similar to exec() but handles the output as a binary stream. This comparison of the three may help you understand them.

But this isn't the end of the story. There is also proc_open(), which allows bidirectional communication between the PHP process and the C process it invokes. This is a bit more complicated, but it may provide a more flexible solution.

Finally, there is a yet more flexible solution: SWIG. While it is not specific to PHP, it does support PHP as well as other languages such as Ruby and Python. As a general-purpose function interface, it is more complicated to use than the others, but if you need this sort of power, it is available.

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

There are actually a number of them out there, at least two of which are actually called 'NASM-IDE'. The more familiar one is probably this one, though it has it's problems - many people dislike it for it's flakiness. Another popular choice is RadASM, which is said to have excellent NAMS support (it is more or less a general Assembly-language editor, with support for several assemblers). I haven't tried it myself so I cannot give much more than that about it - I think I'll give it a try sometime soon, though.

For my own part, I generally use Notepad++ or some similar general-purpose editor (I use EMACS on Linux a lot of the time). I often find that the flexibility of editing several different types of programs in the same environment worth giving up some of the IDE type tools. That, however, is a personal preference and one you might not share.

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

Assembly Language Step-by-Step Programming with DOS and Linux by Jeff duntamen.It is an old book.Like around 2000 !

Ah, that explains it. It's an excellent textbook, but that edition came out before the x86-64 line was introduced; it was talking about Itanium, which was brand-new at the time.

because I wanted to understand how do computers actually work,I started learning assembly.Like how memory,processor work etc.. .It is good to know those before learning a High level language...

Yes and no... every programmer is different, and what some people find helpful others might not. If it works for you, though, I would stick with it. Keep in mind that much of what he talks about in that version of the book is specific to real mode, which isn't very relevant to most modern programming even in assembly.

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

You may find it worth your while to write a general exponentiation procedure rather than multiplying each time manually. While there is some overhead in a function call, and more in looping to get the result, you need to recall that in a real MIPS CPU (as opposed to SPIM), multiplication takes (IIRC) up to 32 cycles - and if you use the mul pseudo-instruction rather than mult , then you could be waiting the whole 32 cycles to get the results back. If you use mult , and then have other instructions before calling mfhi / mflo for the result, you get around this - again, I am not certain if SPIM accurately reflects this, but it is how real MIPS processors work.

Anyway... as I was saying, an exponentiation function that applies tricks such as using shifts for powers of 2 and successive multiplication can probably be a lot faster than simply multiplying n times in a row.

If nothing else, you can use successive multiplication in your code to eliminate a few multiplications:

# Multiply 3*3*3*3 to get the power of 81

	mul $s1, $t0, $t0	# E` = A*A
	mul $s2, $s1, $s1	# E = E` * E` = A*A*A*A

        # Multiply 6*6*6*6*6*6 to get the power of 46656

	mul $s4, $t1, $t1	# F = B*B
	mul $s5, $s4, $s4	# F = (B*B)*(B*B)
        mul $s6, $s5, $s4       # F = (B*B*B*B)*(B*B)

Later, you can use a shift to replace multiplication by …

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

Which book, and in what context? Are you certain it wasn't discussing Itanium processors (IA-64, Intel's first attempt at a 64-bit successor to the IA-32 line - better known as x86), rather than x86-64 processors? The former are indeed very different from the x86 series CPUs, but they never gained a real foothold for precisely that reason (among other things). The x86-64 design, which was developed by AMD and only adopted by Intel much later when it looked like they would be knocked out of their own market, is a derivative of the x86 line, and while there are significant differences, they are still based on the x86 architecture.

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

A relevant quote from Abrash on this topic may clarify things:

Never underestimate the importance of the flexible mind. Good assembly code is better than good compiled code. Many people would have you believe otherwise, but they’re wrong. That doesn’t mean that high-level languages are useless; far from it. High-level languages are the best choice for the majority of programmers, and for the bulk of the code of most applications. When the best code - the fastest or smallest code possible - is needed, though, assembly is the only way to go.

Simple logic dictates that no compiler can know as much about what a piece of code needs to do or adapt as well to those needs as the person who wrote the code. Given that superior information and adaptability, an assembly language programmer can generate better code than a compiler,all the more so given that compilers are constrained by the limitations of high-level languages and by the process of transformation from high-level to machine language. Consequently, carefully optimized assembly is not just the language of choice but the only choice for the l percent to 10 percent of code - usually consisting of small, well-defined subroutines - that determines overall program performance, and it is the only choice for code that must be as compact as possible, as well. In the run-of-the-mill, non-time-critical portions of your programs, it makes no sense to waste time and effort on writing optimized assembly code-concentrate your efforts on loops and the …

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

First off, there's no such thing as a 'hex value'; there are binary values, some of which represent numeric values and some of which represent character encodings. I presume what you want is to display a binary numeric value in a character string as a hexadecimal number.

Let's start with the numeric value itself. given the size of the number you seem to have, and the way you've shown it in you earlier attempt to explicate your intentions, I assume that what you're working with is a 128-bit value (your value used 11 bytes, which means that it won't fit in anything less than 88 bits). Unfortunately, there are no standard C++ variable types that large. You'll need at least two long long variables in a structure or an array, assuming your compiler supports that type; otherwise, you need four 32-bit int variables to hold it.

Just out of curiosity, could you tell us what this is supposed to represent? My initial impression was that it was an IPv6 address, but if so, you wrote it incorrectly (IPv6 addresses are written with sections of two bytes, with leading zeroes elided, so it would have been 4845:4c4c:4f20:574f:524c:44:: or something similar - because there are less than 16 bytes, and you only gave the actual hex values, it's hard to say where the zeroes would go).

Anyway... to print out a numeric value in hex, you simply use the hex manipulator with the output stream before the number to …

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

Could you please be more specific about how getcwd() and sprintf() are failing?

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

Let's start with the second one - the one following the main() function - first. What you have there is a function definition, which gives a name to a function - totalCost() in this case - and declares the type of the value it returns - double - and the parameters of the function ( numberParameter and priceParameter ) which are names for variables that get passed to the function when it is called. They are called 'parameters' because, well, they are analogous to the parameters of a mathematical function - it's simply a traditional name.

Now, let's take a quick look at main() which in this case calls totalCost() like so:

bill = totalCost(number, price);

here, number and price are the arguments of the function - they give the values which are put into the parameters. Each time you call a function, you can give it different arguments. The result of the function is returned and stored in bill , in this case.

Now, there's just one problem with all of this: the definition of totalCost() comes after the definition of main() . How is main() supposed to know what the type and parameters of totalCost() are? That's where the function prototype at the top comes in - it gives a capsule summary of the function, letting main() (and any other functions) know that there is a function called totalCost() around here somewhere, and that it expects arguments of type int and double and that it …

Torf commented: Thanks +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The truth of the matter is, you can write slow code in any language, and it is generally a lot easier to write inefficient code than efficient code. The main advantage of C - and high-level languages in general - is that it is easier to write fast code in them than in assembly.

This does not mean that C is faster than assembly. In the end, all code is running in machine code, regardless of how it is implemented - even interpreted code is running as a machine code program, just as one that happens to interpret some text as a series of instructions. Assembly language is harder to write efficiently, and beating an optimizing compiler takes considerable skill. In the end, however, assembly code isn't simply faster; it is all there really is. Everything else is for giving you a more accessible notation - they improve the efficiency of the programmer, not of the program.

Mind you, on multitasking systems, especially those with virtual memory (which is nearly all of them today), the speed with which a program runs has more to do with the speed of the processor, the system load, and the available real memory, than with the efficiency of the program itself. Furthermore, IMAO, efficiency for event-driven programs is false fire - your program will spend more time waiting on user events (mouse clicks, keypresses) than on actual processor time. Even in CPU-bound code, most of the processing time is usually in a …

~s.o.s~ commented: The last line deserves more up-votes +17
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

(Note: This was previously posted at http://www.ruby-forum.com/topic/3426459#new , but received no responses after four days.)

When attempting to install ruby-debug19 on a Windows 7 partition, I have gotten the following error sequence:

ERROR:  Error installing ruby-debug19:
        ERROR: Failed to build gem native extension.

        C:/Ruby193/bin/ruby.exe extconf.rb
checking for rb_method_entry_t.called_id in method.h... no
checking for rb_control_frame_t.method_id in method.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/Ruby193/bin/ruby
        --with-ruby-dir
        --without-ruby-dir
        --with-ruby-include
        --without-ruby-include=${ruby-dir}/include
        --with-ruby-lib
        --without-ruby-lib=${ruby-dir}/lib
extconf.rb:16:in `block in <main>': break from proc-closure (LocalJumpError)
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:18:in `call'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:18:in `create_makefile_w
ith_core'
        from extconf.rb:32:in `<main>'

I have tried re-installing Ruby (version 1.9.3 p0) and DevKit, but this did not seem to change the result, nor did removing c:\MinGW\bin from the PATH variable. The error remains the same when using the latest version of the debug-base gem (ruby-debug-base19-0.11.26.gem) gets the same result.

Adding the option '--with-ruby-include=C:\Ruby193\include' simply results in the error message:

ERROR:  While executing gem ... (OptionParser::InvalidOption
    invalid option: --with-ruby-include=C:\Ruby193\include

I installed ruby_core_source, but this didn't change the error. I then tried installing the preview version of ruby-debug19x (0.11.30), and got a rather different set of error messages:

Fetching: ruby-debug-base19x-0.11.30.pre6.gem (100%)
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
ERROR:  Error installing ruby-debug-base19x:
        ERROR: Failed to …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hoo boy, you have a bit of a mess here. Where to begin...

Well, first off, let's review the data structure itself. Right now you have a few things that are redundant, and some others that seem to indicate a misunderstanding of the problem. Let's simplify things a little by cutting the redundant information out:

struct classroom
{
	unsigned room_number, number_of_chairs;
	vector<string> students;
	string teacher, Lecture_Name;
	bool windows, projectors;
};

You didn't need a separate students string in addition to the vector of the students names; that gets cut, and student gets renamed to students for clarity. The number_of_students is the same as students.size() , so there is no need to keep a separate variable for it - you just risk running into a problem of the two getting out of sync, so it is better to use the existing functionality for this purpose. You can get whether there are seats available by comparing the number of seats to the number of students, so that doesn't need s separate variable, either. Finally, the problem statement given indicates that whether there are windows and whether there is a projector are both yes/no values, so it makes more sense to use a Boolean variable for each of those.

Next, let me repeat something I said earlier: you need to separate the structure declaration from the main() function. Not only is this just a good practice, it is necessary if you are to share the structure with other functions, something …

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

The reason you can't declare the students array the way you have it is because number_of_students is not constant; a statically-allocated array needs to have a constant size at declaration time.

Probably the easiest solution is the one you've already got in the structure. which is to use a vector<string> for the list of students. You can simply eliminate the existing students member, and use the one you currently have under the name student . The vector will automatically keep track of it's own size, which would be the same as the number of students in the class.

As an additional piece of advice, you're going to want to move the structure type declaration out of main() , as part of the requirements of the project is to write functions that manipulate the structure. You'll also need to be able to declare more than one variable of the structure type, as well.

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

Sigh. That is incorrect. Classes and structs are no different in C++ except for the fact that by default, structs uses 'public' and classes uses 'private' as an access specifier.

cringes at own mistake You are correct, of course, and I should have been more careful in what I wrote.

sigh I make so many mistakes of this sort, I wonder why I even post here if I can't be more accurate...

mrnutty commented: All good, live and learn bro +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I forgot to mention Pelles C, which, if you are using C and don't expect to be using C++ at all, may be the best solution of all.

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

Compilers can be written in pretty much any language - I've written one in Python, for example - though C and C++ are probably the most commonly used ones. There are some specialized tools specifically for writing parsers and lexical analyzers - the best known being LEX and YACC, and their various descendants (flex, bison, ANTLR, etc.) - but you can write a compiler entirely in C++ if you choose to.

As for 'bootstrapping' (also called 'self-hosting'), that would be a a bit more specifically when a compiler is used to compile itself. This is often done as a test of the correctness (or at least consistency) of a compiler's output: you compile the compiler in your existing compiler, then compile it again using the compiler you just wrote, then compile the compiler again using the second compiler's output, and if the resulting object code is identical to that produced in the second step, then you can safely say that it is producing stable object code. It is not a proof that there are no bugs in the compiler, but it does help eliminate a lot of them along the way. This technique goes back at least to 1962, and is still widely used, being popularized by the 'Small C Compiler' article in the 1970s; the GCC compiler build scripts even have an option to do this automatically.

In addition to the links I give above, a paper …

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

While I have to agree with the others that you would be better off using a newer IDE rather than Turbo C++, I understand that you might not have a choice in the matter. Is this for a particular class that requires Turbo C++, or are you using it for personal study? If the former, all we can say is 'good luck'; if the latter, you would be well advised to use a different free compiler/IDE such as Code::Blocks or Visual C++ Express instead.

If you must use Turbo C++ - and again, it is not an ideal solution - then the choices are to either run DosBox, as Ancient Dragon proposes, or set up a virtual machine installation of some older version of Windows (no later than XP) using something such as Microsoft Virtual PC or Oracle VirtualBox.

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

Just how you would do this will depend on the compiler (and IDE) you are using, but in general, you would need to set up a Project (or a Makefile, for compiling from the command line) that would keep track of which files need to be compiled and linked into the executable file. Could you tell us how you are compiling this, and with what compiler and editor?

If you need to review the concepts behind linker and why you don't want to use #include for the code files, you might want to see this post for a somewhat whimsical explanation of inclusion and linking.

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

Structures are intended for grouping data together, which can then be worked on as a unit - you can have pointers to structures, pass them as function arguments and returns, etc. Structures make it feasible to work on more complex data structures such as linked lists, trees, heaps, and so forth.

As FirstPerson says, they are primarily in C++ because they had been in C originally, and C++ started out as a super-set of C. The role of structures has largely been superseded by classes, which have the same basic purpose but have additional features for supporting object-oriented programming (e.g., inheritance).

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

Now hold on though: the OP referred to C rather than C++. It is possible that this was supposed to be posted in the C forum. While this wouldn't change Narue's answer (or Ancient Dragon's), the replies which assume C++ strings wouldn't apply.

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

Well then, assuming that this is the exact assignment that the OP is completing (and it almost certainly is), then the answer is simple: the code as posted is using the wrong data structure.

Burcinerek: you need to replace the array with an unordered_set<> . Rather than adding randomly generated numbers, you should simply fill the numbers in by a normal counting ( for() ) loop, then use the shuffle() method to randomize them. Then you would simply remove them from the set one at a time, giving one of them to each student.

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

By 'this', you mean to give each student a unique ball? What is actually happening?

Has you classwork covered linked lists, or the vector class? This sounds like an exercise aimed at using one of those rather than a basic array (because you can add or remove items from them).

Also, you should add a ' return 0; ' statement at the end of the main() function, just to make sure that it does in fact return a valid value to the operating system.

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

You want to put the struct declaration before the main() function. Then, inside the main() or just before it, you want to declare a variable of the struct type to use.

BTW, you also need to put semi-colons at the end of the function prototypes. That, and your indentation needs work. And you don't want to return a value at the end of a void function.

#include<iostream>
using namespace std;

void showSelection();
void selectItem();

struct Contact
{
    char first_name[20];
    char last_name[20];
    char email[20];
    char phone_no[20];
}


int main()
{
    Contact person;

    int choice;
    showSelection();
    cin>>choice;

    while (choice !=9)
    {
        switch (choice)
        {
        case 1:
            selectItem (list);
        case 2:
            selectItem (edit);
        case 3:
            selectItem (search);
        case 4:
            selectItem (exit);

            break;
        default:
            cout<<"Invalid selection."<<endl;
        }
        showSelection();
        cin>> choice;
    }
    return 0;
}


void showSelection()
{
    cout<<"*** welcome to my phonebook system ***"<<endl;
    cout<<"To select an item, enter "<<endl;
    cout<<"1 for list : "<<endl;
    cout<<"2 for edit "<<endl;
    cout<<"3 for search "<<endl;
    cout<<"9 for exit "<<endl;

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

You say that the program crashes when it exits, which implies that the problem is in how you are cleaning up the program run, most likely in when you are deleting the nodes of the list. Can you post your code where the problem is occurring?

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

Not as such, no. The standard formats for floating-point numbers is such that this wouldn't work. With most x86 compilers, a double is 64 bits long, with one bit for sign, 11 bits for the exponent, and 52 for the significand (that is, the value to the right of the binary point). This format is dictated by the floating-point hardware, so that alone presents a limitation on conventional floating-point numbers. To span the numbers across an array like you suggest would require the compiler to separate the different bit sections out of each number, then span them separately. This simply isn't practical, and even if it were, you would need a compiler that supported it in some fashion.

How large a number do you need? Most compilers for C (and some for C++) support the long double type, which on the x86 uses an 80 bit extended double format. This may be large enough for your purposes.

Realistically, your best solution may be to use a bignum library such a the GNU Multiprecision arithmetic library (GMP). It is widely used for such purposes, being a key component of some important programs (e.g., GCC).

OTOH, this may not be acceptable if you are working on a homework project, so it depends on what you are doing. If it is homework, and multi-precision math is the objective of the assignment, you'll have to write your own bignum code - and as …

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

Could you post the project in a zip file so I can download it, to make sure it's a compiler issue and I didn't just write a typo?

Certainly.

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

Which compiler/IDE are you using? I've been testing using Code::Blocks and the latest version of MinGW GCC (4.6.2) under Windows 7, but if your testing in, say, Visual Studio, or GCC for some other operating system, you may be getting different results.

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

Thank you, those help quite a bit.

Did you have any problem compiling with those changes? I had to move the Nationality and GameClass into PlayerClass.h and remove the cyclical #include "battlefront.h" from PlayerClass.h as well; once I did that, I got it to run, at least to the point that an image comes up on the screen.

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

Now that I mention it, you might find it quite enlightening to study the MIPS instruction set, as it is the classic RISC architecture, and widely studied in Computer Systems courses. It is a much easier assembly language than the x86 instruction set, yet is for a real-world CPU (even if it is mostly used for game systems and cellphones these days). There are a number of MIPS simulators for Windows, the best known probably being SPIM (though it isn't the best, it is fairly easy to use) - which gives you another virtual machine example to study, albeit a complex one.

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

I used switch() for the main instruction system mainly because it was convenient and because it reflected the overall structure of the operation somewhat better - it is clear that the switch() operation was a single grouping of related operations, whereas separate if() statements, even when grouped together, are not necessarily so connected.

In truth, I was never seriously considering using ad hoc if() statements, though I had considered using a jump table; I decided against that mainly because most compilers will convert a switch() into a jump table anyway, and also because my bytecode is fairly sparse, meaning that there would be a lot of no-op cases in such a table.

As for efficiency, that depends on the particular compiler - though as I said, most compilers will turn a switch() into a jump table, (at least when all of the cases are completely filled), which is quite a time-efficient way of matching a value to an operation.

If I were implementing a virtual instruction set and needed to squeeze all the performance I could out of it, I would probably do some bit-masking tests to isolate the different groups of instructions - most instruction sets, real or virtual, are designed so that related groups of instructions have some bit-pattern in common with them, as can be seen in the MIPS processor family, a cleanly-designed real world CPU family - then use either switches or explicit jump tables to find the specific instructions.

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

One last thing, by "sprites" do you mean the image files, like UK_Body.png, etc.?

Yes.

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

OK, I took the time to download SFML (I was curious about it, anyway, so it wasn't a big deal), and compiled and tested your program. After setting some breakpoints at various places, I found that it is raising a SIGSEGV (that is, a segmentation violation) in the initialization of PlayerA, on the line

PlayerFeet.SetImage(iFeet);

The call stack at the point where it segfaults reads like so:

#0 00A18C6B std::_Rb_tree_decrement(__x=0x406044) (../../../../gcc-4.4.0/libstdc++-v3/src/tree.cc:89)
#1 00A02CAF std::_Rb_tree_iterator<sf::ResourcePtr<sf::Image>*>::operator--(this=0x28fd48) (d:/programmes/mingw-4.4/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_tree.h:199)
#2 00A10E3E std::_Rb_tree<sf::ResourcePtr<sf::Image>*, sf::ResourcePtr<sf::Image>*, std::_Identity<sf::ResourcePtr<sf::Image>*>, std::less<sf::ResourcePtr<sf::Image>*>, std::allocator<sf::ResourcePtr<sf::Image>*> >::_M_insert_unique(this=0x406040, __v=@0x28fdfc) (d:/programmes/mingw-4.4/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_tree.h:1179)
#3 00A09B48 std::set<sf::ResourcePtr<sf::Image>*, std::less<sf::ResourcePtr<sf::Image>*>, std::allocator<sf::ResourcePtr<sf::Image>*> >::insert(this=0x406040, __x=@0x28fdfc) (d:/programmes/mingw-4.4/bin/../lib/gcc/mingw32/4.4.0/include/c++/bits/stl_set.h:411)
#4 009C83A6 sf::Resource<sf::Image>::Connect(this=0x406040, Observer=...) (../../include/SFML/System/Resource.inl:77)
#5 009C4678 sf::ResourcePtr<sf::Image>::operator=(this=0x4062cc, Resource=0x406040) (../../include/SFML/System/ResourcePtr.inl:102)
#6 00922CB4 sf::Sprite::SetImage(this=0x406220, Img=...) (D:\dev\sfml\sdk\SFML-1.6\src\SFML\Graphics\Sprite.cpp:72)
#7 004016CA PlayerClass::PlayerClass(this=0x406220, natl=UK) (C:\Users\Schol-R-LEA\Documents\Programming\Projects\Quick Tests\Battlefront\PlayerClass.cpp:15)
[color=red]#8 00402D16  __static_initialization_and_destruction_0(__initialize_p=<optimized out>, __priority=<optimized out>) (C:\Users\Schol-R-LEA\Documents\Programming\Projects\Quick Tests\Battlefront\Battlefront.cpp:13)[/color]
#9 00000000 _GLOBAL__sub_I_MainWindow() (C:\Users\Schol-R-LEA\Documents\Programming\Projects\Quick Tests\Battlefront\Battlefront.cpp:29)
#10 0040244F    __do_global_ctors() (../mingw/gccmain.c:59)
#11 00401098    __mingw_CRTStartup() (../mingw/crt1.c:236)
#12 00401284    mainCRTStartup() (../mingw/crt1.c:264)

The most relevant part of the call stack is highlighted in red; it shows that the code where it is failing is being called in the static initialization, which takes place before main() begins.

Now, the image files are supposed to get loaded in MatchSprites(); however, because you are initializing PlayerA as a global variable, the c'tor is actually being called before MatchSprites() has run (and in fact before the beginning of main(), with the result that iFoot hasn't been initialized at the time when you are setting the the image as part of the PlayerA object, with the result that an invalid pointer is being passed …