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

Fon_1: Just to clarify the matter, are you looking for any C compiler, or specifically looking for an installation of the Dev-C++ Integrated Development Environment (which is not itself a compiler - the compiler it uses is the aforementioned GCC) and all of the additional libraries that go with it?

In the former case, I would recommend Pelles C as a good C compiler and IDE combination. It is specifically a C compiler, and unlike (say) GCC, it will not compile C++, but that may be just what you need. It includes a fairly complete set of libraries, though if you need a specific one that it doesn't include you may have some problems.

If it is the latter, then I recommend getting the Orwell Dev-C++ distribution; the older Bloodshed Dev-C++ version is a decade out of date. As for the packages that go with it, if you RTFM, you'll find that it includes a package manager that should allow you to download most of the tools you might want.

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

Actually, 'fault tolerance' has more to do with gracefully recovering from exceptional situations than with avoiding them entirely. Setting up exception blocks around fault-sensitive code (e.g., pretty much all I/O) is a good starting point, but not sufficient in and of itself; you have to know how to handle the exceptions, not just trap them.

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

That was the one I was thinking it might be, but I was hoping the OP could confirm this.

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

When posting any request for help with an assembly language problem, we ask that you provide some crucial information:

  • The operating system (Windows, Linux, MacOS, etc.) the program will be running under, including the version,
  • The assembler you are using, including the version,
  • the bit width being targetted (usually 8, 16, 32, or 64 bits), and
  • If you are using an emulator, and if so, which one and what architecture it targets

The reason this is important is that, unlike most of the other languages discussed on the DaniWeb, 'assembly language' is not a single, common, portable language, but rather a class of languages. An assembly language is primarily a human-readable analog for the machine operation codes (opcodes) of a particular processor family, and is specific to that type of processor. While the overwhelming majority of personal computers use some member of the x86 family, they are by no means the only type in use; most mobile phones and tablets, for example, use an ARM processor, which is entirely different from the x86 architecture.

Also, some processors have different bit widths in different models, or in different modes; for example, the original PC ran in a 16-bit 'real' mode, but later models of the x86 family introduced a 32-bit 'protected' mode, and later still, a 64-bit 'long' mode. Each of these modes have their own distinct ways of handling registers, data sizes, and so forth, so it is important to know what the word size is.

Furthermore, there are …

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

OK, what have you tried so far?

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

What happens when you try to run it?

(BTW, there seems to have been some kind of problem when you pasted the code, but don't worry, it isn't hard to see to tell what the code actually is. These things happen.)

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

In a post earlier today, I asserted that Intel wanted to get rid of the x86 platform. It occurred to me that a lot of folks may not understand this claim, but there are good reasons for it. They have made at least three attempts at doing so, in fact, starting as early as 1986, but the momentum of the existing hardware and software base has made it impossible for them so far.

Why would Intel want to kill the goose that laid the golden egg? Simple: it isn't the cash cow most people think it is. Most of their real business isn't in the desktop systems, it's in embedded systems (including mobile systems, these days), and they never intended to get into the small computer market in the first place. In 1977, when they first began designing the 8086, the home computer market was tiny, the reserve of crazy electronics enthusiasts who mostly built their own systems from kits (there were a handful of pre-built systems on the market, but even those were mostly seen as a novelty). That market was too problematic and too small for them to waste much time on; as far as they were concerned, they were making microcontrollers, thank you very much, and this whole business of 'microcomputers' was a passing fad. It probably would have been a fad, if Apple hadn't come along, but even then Intel wasn't very interested, as Apple was buying their microprocessors from a competitor. It wasn't until IBM …

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

Actually, this is what I believe is now called 'C++ for .Net Applications', what used to be called 'Managed C++' (or as I always preferred, 'Mangled C++'). It is a dialect created by Microsoft and specific to their systems, which runs on the .Net CLR. It is really a new language, distinct from standard C++, but MS never wanted to admit this as it would put off those who didn't want to work with .Net (and to silently lock client-programmers into their non-standard dialect without them realizing it). It exists primarily because they were never able to move all the system operations to .Net as they originally planned, and so continued to need ways to mix .Net code with native code (as I understand things, their real goal in creating .Net was to give the x86 platform the heave-ho - something nearly everyone, including Intel, would like to do - by making Windows itself run in the .Net pseudo-machine a la the old UCSD Pascal OS, but it never came close to working since it would mean losing the entire backwards compatibility structure that Windows' success is built upon, and the goal was eventually abandoned).

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

/me covers ears from the shouting

As Moschops said, it depends on the operating system, on the C compiler and libraries you are using, and in some cases, the specific type of console you are working with. I'm going to guess that you are working with a DOS console running under Windows, possibly in a DOS emulator such as Dosbox. I'll further speculate that you are using Turbo C or Turbo C++, since hardly anyone working with modern tools is going to be interested in doing this. Is this a fair assumption?

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

Pseudo-code doesn't work; that's the whole point of it. It is a higher-level description of a problem without the details that would make it a running program. Pseudo-code isn't a specific language - it is just a description of the program in a way that resembles actual code, but omits the details. There is no specific syntax or rules for pseudo-code, you make it up as you go along.

If you don't mind me asking, why do you need pseudo-code for a program that already exists? Usually one writes the pseudo-code first, and then uses that as the design for the actual program, not the other way around. Did you assignment call for you to lay out a design in pseudo-code, and then write the program? If so, how did you come to skip that step?

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

I apologize for having hurt your feelings; as I said, I was pretty sure you hadn't meant it that way, but it can be hard to tell sometimes. We do get a lot of people who are asking for their work to be done for them, so there's a bit of a tendency to assume the worst. I am sorry for doing that to you.

As for displaying the names of the files... well, we'd need more information about just what you are trying to do. If it were simply a matter of displaying the names of the files used during the current run of the program, it would be very simple: you could simply keep a vector<string> of the file names that have been entered, and print the strings in a loop (vector is a template class which acts as an array that can automatically grow or shrink as you need it to). However, I am assuming you want to be able to get the files that the program has previously generated, which presents a few problems.

First off, you would have to know where the files in question are, either by checking the current working path, or by having some directory where you can look for them, or by letting the user choose where they should be stored. You would also want to have some way of telling which files are the data files for this program, which usually means picking a file extension for them.

But that's …

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

CSprogA: While I would have worded it rather differently, I have to agree with Hassan_12 on this. You would have to tell us what help you need, and ask meaningful questions about how you can solve the problems you are having, before we can have any hope of helping you in a way that wouldn't constitute a hand-out. While I am pretty sure that you honestly did come for advice rather than a quick fix, given some of what you said, it did come off as begging rather than a serious request. Try to explain what the problems you are having in more detail, if nothing else.

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

No one here will do your homework for you. Please demonstrate that you have at least tried to solve the problem first prior to posting here.

<rant>
Seriously? This is beyond trivial. If you had been paying attention in class at all, or even opened your textbook just once, you could have completed this assignment in less time than it took to post this question. This is laziness of the worst kind, and we at Daniweb aren't going to reward you for it.
</rant>

Sorry for the rant, but I am not kidding - this should take even a rank novice programmer less than five minutes to complete using just paper and pencil. You have wasted both our time and yours by bringing this here.

rubberman commented: Well put! Some students can't do the work without looking over the shoulder of better students... +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Thomas_25: rubberman and deceptikon have, indirectly, brought up a good point: is a doubly linked list what you actually need for your purposes, or would an ordered tree structure of some kind (e.g., a priority queue, an AVL tree, a splay tree) serve your needs better? Now, obviously, if this is for a homework assignment on doubly-linked lists, there's not going to be any leeway in this regard, but otherwise, you might want to consider just what data structure fits the problem best. What is the project you are looking to apply this to?

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

suraiyaparveen: You won't get it, for two reasons. First, no such program exists - those are all things that need to be done manually, not programs to be written. Second, even if it were feasible to do those things programmatically, we wouldn't give it to you without some evidence that you had put in a good faith effort to solve the problems on your own first. Daniweb is not a free homework cheating service, and no one here is going to do your work for you.

Also, don't go reviving long-dead threads. Thread necromancy is considered extremely rude on pretty much every message board on the web, and is just one more reason for most of the people here to ignore you or worse.

rubberman commented: Ah! Digital necromancy! Time to raise the long dead! +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've ended up pulling this boilerplate reply out twice in 24 hours, sheesh

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 demanding that we provide you with code with no evidence of any effort on your part 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.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be …

rubberman commented: Remedial basket weaving? :-) A great course as I recall! +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

For the sake of readability, let's start by separating the class declarations and implementations from the main program, and get the whole into some semblance of a consistent indentation:

matrix-list.h

#ifndef MATRIX_LIST_H
#define MATRIX_LIST_H 1

class Node
{
private:
    int row;      // different data type for other apps
    int column;
    int value;
    Node *next;   // the link pointer to next item

public: 
    Node(int x=0,int y=0,int z=0,Node * ptr=NULL); // constructor
    int getRow();
    int getColumn();
    int getValue();
    Node *getNext();
    void setValue(int z);
    void setNext(Node *ptr);
};

class List
{
private:
    Node *head_ptr;
    Node *tail_ptr;
    int numOfItems;

public: 
    List();               // constructor
    int size( );  
    Node *getHead( );  
    Node *getTail( );
    bool isEmpty( );
    Node *itemAt(int position);
    void removeHead(); 
    void removeTail(); 
    void insertHead(int x, int y, int z);     
    void printList();
};

#endif

matrix-list.cpp

#include <iostream>
#include "matrix-list.h"

Node::Node(int x, int y, int z, Node *p):
    row(x), column(y), value(z), next(p)
{
    return;
}

int Node::getRow()
{
    return row;
}

int Node::getColumn()
{
    return column;
}

int Node::getValue()
{
    return value;
}

Node * Node::getNext()
{
    return next;
}
void Node::setValue(int z)
{
    value = z;
}

void Node::setNext(Node *ptr) {next=ptr;};


List::List()
{
    head_ptr= NULL;
    tail_ptr=NULL;
    numOfItems=0;
}

int List::size()
{
    return numOfItems;
}

Node * List::getHead()
{
    return head_ptr;
}

Node * List::getTail()
{
    return tail_ptr;
}

bool List::isEmpty()
{
    return (numOfItems==0);
}

Node *List::itemAt(int position)
{
    if (position < 0 || position >= numOfItems) 
        return NULL;
    Node * currentPtr = getHead( );
    for(int k=0; k != position; k++)
        currentPtr = …
rubberman commented: Schol-R-Lea, you are much more patient that I am! +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

IMAO, the best approach to sorting a linked list is not to let it get out of order in the first place. While inserting the nodes in order is slower than pushing them to the head of the list and then sorting, it has the affect of amortizing the sorting over the course of the program's operation, which can prove more important than sheer operational speed. More importantly, it means that there is never any need to repeat the sorting, which is often the case if the list is being actively changed over time.

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

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.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on …

rubberman commented: Good rant! :-) +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

No, the DBMS is the SQL library or process that the application interfaces with to manipulate the database. For example, MySQL is a DBMS, but an application that uses MySQL would not be.

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

how can i make a calculator using function and procedure..

With all due respect, this is far too broad a question for us to try to answer, even if we were inclined to do the work for you in the first place - which we are not. NathanOliver's answer is about the most any of us can give without a lot more details about what you need to do, and a lot more evidence that you have tried to solve the problem yourself.

Whatr specifically do you need help with? If you are having trouble understanding how functions work, there are plenty of older posts on the subject here; a search should turn up dozens.

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

The elaborate on DaveAmour's answer, you should know that C (the predecessor of C++) does not have a built-in boolean datatype, and until the C99 standard didn't have a standard defined one either. Thus, it has long been the convention in C to use int variables as booleans, with 0 for false and any other value for true.

While C++ has always had a bool type, a lot of C++ programmers who had started out in C never got into the habit of using it, and a lot of C programs which were converted to C++ were never changed to use it, either.

The variable name flag (or some variation thereof) generally indicates that the variable is being used as a boolean value, and more specifically, a flag value, that is, one used to indicate a particular state or state change in the program. In file formats, an int value may actually hold several packed flag fields, with the individual bits being treated as separate boolean values. However, in the context you are describing, it is more typical for it to hold just a single boolean value.

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

The first step is to import the GUI library you mean to use. Since a set of bindings for Tk is included with the Python standard library, that's probably the one you'll want to use; let us know if you want a different toolkit such as wxWindows or Qt.

Assuming for the moment that you're using tkinter, You probably want to start with one of the tutorials on the Python website. To give a thumbnail sketch of what you'd need to do, you need to import tkinter,

import tkinter as tk

(I chose to shorten the tkinter package name rather than import it en masse, because even in a simple program like this it is better to limit namespace pollution as much as possible.)

Geberally, you will want to define a subclass of the Frame widget next, as a way of organizing the widgets that will go in said frame. In this case, you will want to make the number to be guessed at and the number of guesses member variables of the frame as well:

class GuessingGame(tk.Frame):
    def __init__(self, master=none)
        tk.Frame.__init__(self, master)
        self.target = random.randint(1, 50)
        self.tries = 0
        self.correct = False
        self.pack()
        self.createWidgets()

You would then define the methods for setting up the widgets, event handlers and so forth.

Once you've defined the GuessingGame class, you would then create a Tk root widget in the main program:

if __name__ == "__main__":
    root = tk.Tk()
    game = GuessingGame(master=root)
    game.mainloop()
    root.destroy() …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's see, old style headers with extensions, <conio.h>, void main() - let me guess, your professor is using Turbo C++ as your compiler?

/me checks OP's locations Ah, Pakistan, that explains that. This comes up a lot, and the answer is that there's nothing to be done about it. Pity, there's really no chance of you being allowed to use something more modern there, as the university system in Pakistan (like that in India) standardized on Turbo C++ decades ago and won't budge an inch on the subject. It's unfortunate, as it means you are being taught a version of C++ that is nearly twenty years out of date, and using a compiler so old that you can't even install it on newer PCs without using a DOS emulator, but as long as you are going to class at a university in your country, there simply isn't any alternative.

The first piece of advice is to be more careful with indenting your code. Proper indentation makes a world of difference in how readable the code is. The specific indent style is less important than being consistent about it; the whole point is to make the different parts of it stand out.

The other thing is that, no matter what the compiler accepts, and no matter what your professor may have told you, void main() is not valid C++. In C++, the main() function must always return an int, either zero when the program succeeds or an error code …

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

As Moschops said, the NULL pointer is essentially a marker. Setting a pointer to NULL is a way of indicating the pointer is in an unusable state.

Now, as for it's uses, they mostly relate to handling dynamic memory. You generally want to initialize any pointer that you don't have an immediate value for to NULL, as an uninitialized pointer may or may not point to usable memory. If it is pointing to unusable memory, accessing it is almost certain to cause a memory violation exception such as a segmentation fault. and if it does point to usable memory, you won't know where it is pointing to, which mans that accessing that memory through it, or (even worse) changing the value of that memory could have unpredicatable results. To prevent this, you generally want to set a pointer to NULL, which is guaranteed to segfault if you access it; it is better for the program to fail outright in most cases than to continue in an unknown state. More importantly, because NULL is a known value, one which is always invalid, consistently setting unused pointers to NULL lets you check the state of the pointer. If you test the pointer's value against NULL before attempting to dereference it, you will know if the pointer is usable or not.

It is also important when working with dynamically allocated compound data structures, such as linked lists or trees. The usual practice is to use the NULL pointer to indicate the end of …

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

You're correct that gotoxy() is specific to the Borland compilers; there's no standard equivalent for it, exactly, but for this purpose, the code you have is good beginning. I would recommend making a few changes to get it working:

void draw_box(int width, char top, char sides, char bottom)
{
    cout << top 
         << setw(width - 2) << setfill(top)
         << top << endl;

    cout.fill(' ');
    for(int i = 0; i < width; i++)
    {
        cout << side
             << setw(width - 1) << right << side
             << endl;
    }

    cout << bottom
         << setw(width - 2) << setfill(bottom)
         << bottom << endl;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, did your instructor actually teach you to use goto, and more importantly, were you actually directed to use it? I would find it deeply concerning if a professor were to even mention goto in an introductory course. Actually teaching its use is simply unacceptable.

The main problem with goto is that it is unstructured; it can be used (and abused) to create an incomprehensible flow of control if it isn't used with great care. The goto statement is more powerful than is generally needed for flow control, capable of creating labyrinthine programs often called spaghetti code because of the twists and turns it takes.

It also interferes with the ability of the compiler to produce optimized code; because it is harder for the compiler to analyze, it means that many optimization techniques cannot be applied.

More importantly, it is simply unnecessary for ordinary flow control - more structured alternatives such as while() and for() combined with restricted forms of goto such as continue or break can express almost all flow processes needed even more effectively. Most newer languages don't even provide goto statements because of the potential for misuse, and it is a once-in-a-career event for a C/C++ programmer to find themselves in a position where they would want to use it, something you would do only if all of the alternatives were worse. There are some exceptions, where goto makes the code easier to read - certain kinds of state machines, for example …

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

Ah, there seems to be an issue with terminology that is confusing both you and us. To clarify, a struct is not a function; it is a data structure declaration. By referring to multiple functions, you got us wondering if there were part of the code that was missing.

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

As rubberman said, your statement doesn't make much sense. Could you please explain a little clearer just what it is you need help with?

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

In C, you cannot directly compare compound structures such as strings the way you can simple values such as ints or doubles; or rather, you can in the case of strings, but you would end up comparing the memory addresses where the strings begin rather than the strings themselves.

What you need to use a function that iterates through the strings and compares them element by element. Not surprisingly, the standard string library includes a function for just this purpose, namely strcmp(). However, there's a catch: strcmp() does not return a boolean result, but instead compares the strings lexicographically. If the strings are equal (i.e., they hold the same characters), then strcmp() returns 0; otherwise, it returns -1 if the first string comes earlier lexicographically than the second, otherwise it returns 1. For example,

strcmp("abc", "abd")

would return -1, while

strcmp("xyz", "mno")

would return 1.

The practical upshot of this is that you need to change the if() statement to read something like this:

if((strcmp(Worker_name, worker1.Worker_name) == 0)
  || (strcmp(Worker_name, worker2.Worker_name) == 0))

As an aside, I would recommend against passing any string directly to printf(), as it can be a security risk in some cases. Instead, use

 printf("%s", Worker_name);

Finally, I would strongly suggest that you remove the reference to <conio.h>; not only aren't you actually using any console functions, the header itself is non-standard, and only a handful of now long outdated compilers ever supported it in the first …

Seandean_1 commented: it is printing worker name doesn't exist +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While the program looks good functionally, I would like to make some stylistic suggestions.

  1. You generally want to separate the functions which operform computation from those which do input and output. This principle of decoupling serves to make the program more modular and easier to fix and modify. Separating model from presentation is an important factor in making code reusable, as well, and thus it is a good habit to get into.

  2. The opposite principle, encapsulation, says that whenever possible, related data should be bundled together into a composite structure, and that the operations on the data structure should be bundled with it as well. Again, this makes the code more modular, by separating concerns. If you have covered structs or classes in your coursework, it would make sense to define a Coordinate structure (either a struct or a class) which can be passed around and operated on as a unit.

  3. It is much, much better to use explicit function returns rather than passing values back via reference parameters; it makes it clearer what the purpose and value of the function is if the function is returning a value explicitly. Reference passing of return values is based on side effects, and often opaque ones at that; unless you thoroughly document the reference side effect, future maintainers may not even notice it, and even then misunderstandings tend to creep in. This makes for another reason to bundle the data into structures - you can pass a compound structure via function return, …

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

For what it is worth, here is my full solution, which may or may not make enough sense to you to give you a leg up:

#!/usr/bin/python3
# Rock Paper Scissors, Project 2, Tadd O'Bannion

import sys
import random

ROCK = 0
PAPER = 1
SCISSORS = 2

choices = ['Rock', 'Paper', 'Scissors']

def main():
    print("-" * 50)
    print("Welcome to the wonderful world of Paper Rock Scissors! ")
    print("-" * 50)
    print(" 1) One Player Game ( One human playing against the computer.) \n")
    print(" 2) Two Player Game ( Two humans playing against each other.) \n")
    print("    Choose game type or press ENTER to quit game. \n")
    print("-" * 50)

    menuChoice = input("Please enter a choice from the above menu: ")

    print("*" * 40)
    print('You have decided to ', end='')

    if menuChoice == '':
        print('exit the game. Goodbye.')
        sys.exit()

    elif menuChoice == "1":
        print("play a one player game against the computer.")
        print("*" * 50)

        player1_name = 'Human Player'
        player2_name =  'Computer'
        player2_choice = random.choice([0, 1, 2])

        print_menu()
        player1_choice = read_menu_choice(0, 2)

    else:
        print ("play a two player game against another human.")
        print("*" * 50)
        player1_name = 'Player 1'
        player2_name = 'Player 2'

        print(player1_name)
        print_menu()
        player1_choice = read_menu_choice(0, 2)
        print()
        print(player2_name)
        print_menu()
        player2_choice = read_menu_choice(0, 2)


    print_player_choice(player1_name, player1_choice)
    print_player_choice(player2_name, player2_choice)
    winner = print_match_results(player1_name, player1_choice, player2_name, player2_choice)



def print_menu():
    for n in range(3):
        print(" {0}) {1}".format(n, choices[n]))
    print()


def print_match_results(player1_name, player1_hand, player2_name, player2_hand):
    outcome = ['Tie',
               'Paper covers Rock',
               'Rock smashes Scissors',
               'Scissors cuts Paper']

    combinations = {ROCK:     {ROCK: [0, …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops, I just noticed that I dropped the player2_hand == part of the each of the inner elifs in that second function. My bad.

def print_match_results(player1_name, player1_hand, player2_name, player2_hand):
    ROCK = 1
    PAPER = 2
    SCISSORS = 3

    outcomes = ['Tie',
                'Paper covers Rock',
                'Rock smashes Scissors',
                'Scissors cuts Paper']

    outcome_str = '{0}, {1} wins!'

    if player1_hand == ROCK:
        if player2_hand == ROCK:
            print(outcome[0])
        elif player2_hand == SCISSORS:
            print(outcome_str.format(outcome[3], player1_name))
        else:
            print(outcome_str.format(outcome[1], player2_name))

    elif player1_hand == PAPER:
        if player2_hand == PAPER:
            print(outcome[0])
        elif player2_hand == ROCK:
            print(outcome_str.format(outcome[1], player1_name))
        else:
            print(outcome_str.format(outcome[3], player2_name))

    elif player1_hand == SCISSORS:
        if player2_hand == SCISSORS:
            print(outcome[0])
        elif player2_hand == PAPER:
            print(outcome_str.format(outcome[3], player1_name))
        else:
            print(outcome_str.format(outcome[2], player2_name))            
    print()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem is quite simple: your indentation is off. Lines 25-65 need to be one level of indent to the right.

Please don't tell me how to shorten it, I want this to be a very understandable (from a very new beginner perspective) program so I want to keep it simple.

Actually, shortening it in certain places would actually make it easier to understand, beginner or no, just by reducing repetition. For example, just this one function would make the program easier to read while removing several repeated sections of code:

def print_menu():
    print(" 1) Paper")
    print(" 2) Rock")
    print(" 3) Scissors")
    print(" 4) Quit")
    print()

A slightly more elaborate, but even more useful, example would be:

def print_match_results(player1_name, player1_hand, player2_name, player2_hand):
    ROCK = 1
    PAPER = 2
    SCISSORS = 3

    outcomes = ['Tie',
                'Paper covers Rock',
                'Rock smashes Scissors',
                'Scissors cuts Paper']

    if player1_hand == ROCK:
        if player2_hand == ROCK:
            print(outcome[0])
        elif SCISSORS:
            print("{0}. {1} wins!".format(outcome[3], player1_name))
        else:
            print("{0}. {1} wins!".format(outcome[1], player2_name))

    if player1_hand == PAPER:
        if player2_hand == PAPER:
            print(outcome[0])
        elif ROCK:
            print("{0}, {1} wins!".format(outcome[1], player1_name))
        else:
            print("{0}, {1} wins!".format(outcome[3], player2_name))

    if player1_hand == SCISSORS:
        if player2_hand == SCISSORS:
            print(outcome[0])
        elif PAPER:
            print("{0}, {1} wins!".format(outcome[3], player1_name))
        else:
            print("{0}, {1} wins!".format(outcome[2], player2_name))            
    print()

At this point, though, we might be pushing things a bit for you, so if you don't quite get it feel free to ignore this.

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

I would add that the Travelling Salesman Problem (which this could be, depending on you interpret the traversal requirement) is known to be an NP-Hard problem, so even if you succeed in getting it to work, it may have quite a long run time depending on how many nodes the graph has to cover. Of course, you could just try proving P=NP and thus showing that a shorter run time may be possible, but that's rather a tall order to fill...

rubberman commented: As in a PhD thesis problem? :-) +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

<RANT>
Something has been nagging me about this problem set since it was first brought up, and I think I've figured out what it is: the assignment itself.

It's just a stupid way of doing this. Period.

Seriously, no experienced programmer would solve this problem like that. Ever. This is the sort of thing report generators are for, and report generation has been a solved problem since the 1960s. You would have to be out of your mind to hand-code something like this, because doing so is a terrible waste of time and effort when you could have it done in a fraction of the time with better results using off-the-shelf tools.

I know it is for a class assignment, but that just makes it worse. It is a poorly constructed problem set that teaches all the wrong lessons, and should never have come across any student's desk anywhere. It would make more sense to teach how to design the blasted report generator itself than to teach students to manually write reports, and honestly, just as fast and probably easier on the students.

The professors - and there are many of them - who teach this way are both lazy and incompetent, and should have never have been allowed to set foot in a classroom in an instructor's role. I don't care how good a researcher they are, if they cannot teach in a classroom setting, they shouldn't be required to.

This whole project is symbolic of the horrid …

NathanOliver commented: So true. This should be a DB and report software +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

write a program for left recursion?

Setting aside the fact that you are asking us to do your work for you, which is against the general policy of Daniweb, this sentence (fragment) doesn't make much sense.

I assume what you meant was that you need to write a parser that handles left recursion in the target grammar. There are two basic approaches to doing this, but neither of them a simple, and they certainly aren't something even the wizards of Daniweb could just whip up, at least not without knowing the grammar in question.

The first approach is to write a bottom-up parser, assuming an LR(k) grammar. However, writing a such a parser by hand simply isn't feasible; they are usually generated, which means you would need to write a parser generator rather than a parser per se. That, needless to say, is a lot of work, and we'd need to see the grammar first to know just what type of parser would be suitable.

The other alternative is to convert the left recursions to right recursions, making it feasible to write a top-down recursive-descent LL(k) parser, which is pretty much the only type suitable for writing by hand. That isn't an easy thing to get right, and no matter what the working grammar will still differ subtly for the language's reference grammar. This is probably what you wanted, but if so, where's the grammar to transform?

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

From what the OP is saying, I expect what they want is to replace

string id[MAX_SIZE];
double cmarks[MAX_SIZE];
double fmarks[MAX_SIZE];

with something like this:

struct student_grade
{
    string id;
    double cmarks;
    double fmarks;
};

student_grade students[MAX_SIZE];

This is sensible; not only does it structure the data better, it makes it feasible to sort the structs as a unit, keeping the data for each student together.

I think what they wanted to know is how to access the elements of the array of structs. Fortunately, this is quite easy:

students[this_record_index].id = "d3203032sd1";
students[this_record_index].cmarks = 82.3;
students[this_record_index].fmarks = 73.7;

Simple! I will however, give you a piece of advice: if at all possible, use a std::vector<> instead of a fixed array whenever there is any question of how large the array might have to become.

std::vector<student_grade> students;
student_grade* student;

while (infile.good() && !infile.eof())
{
    student = new student_grade();
    infile >> student.id >> student.cmarks >> student.fmarks;
    if (infile.error())
    {
        break;
    }
    students.push_back(student);
}

The std::vector<> template is more efficient memory-wise, and avoids the possibility of overrunning the array.

ddanbe commented: Great advice! +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

soe win: You may want to read this blog post if you aren't clear about what the Solution folder is and how to work with it. While the post covers an earlier version of Visual Studio, the principles have not changed much.

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

The reason it isn't printing the rest of the list is because... you don't have it printing the rest of the list. Try the following:

void printBackwards(ListNodePtr currentPtr)
{
    // if list is empty
    if(currentPtr==NULL) {
        puts("List is empty.\n");
        return;
    } // end if
    else if ( currentPtr->nextPtr != NULL ) {
        printBackwards(currentPtr->nextPtr);
        printf("%c --> ", currentPtr->data);   // printing the intermediate data here
    } // end else if
    else {
        puts("\nThe list in reverse is:");
        printf("%c --> ", currentPtr->data);
        puts("NULL");
    }
} // end function printBackwards

In addition, I think you'll find that there is a problem in the insert() function; you never set the newPtr->prevPtr value.

    else { // insert new node between previousPtr and currentPtr  
        previousPtr->nextPtr = newPtr;
        newPtr->nextPtr = currentPtr;
        //  should have "newPtr->prevPtr = previousPtr;" here
    } // end else
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As Moschops said, te stream insertion and extraction operators are usually implemented as free functions that is are friends of the class, rather than as members, but it would be useful to understand why this is the case. The reason you can't have it as a member operator is because in a class member function, the this pointer is an implicit argument to the function; in an operator, this means that the left side argument is assumed to be the object being operated on. However, for the stream out operator, you want the operator to act on the ostream reference as the left-hand argument, not the object being sent, so in order to get the desired result, the operator cannot be a member of the class it operates on.

In addition, you must explicitly scope the ostream& declarations, rather than relying on using namespace std;. You should never have a using namespace std directive in a header, in fact, for this a several other reasons having to do with namespace pollution, and using namespace std in general is a poor practice even in source files. The whole purpose of separating the standard library members into a separate namespace is to avoid collisions with user-defined functions, and wholesale application of using namespace std; undermines this. All references to the standard library functions should be explicitly scoped, strictly speaking, including such C-style functions as pow() or printf(), though most compilers let you cheat with the C library functions as a …

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

Adding to what I wrote earlier, here's a simple trick to simplify the printout of the individual hands:

char* get_hand_name(hand h)
{
    char names[][] = {"Rock", "Paper", "Scissors"};

    return names[h];
}

char* get_result_description(outcome result)
{
    char descriptions[][] = {"Draw.", "win for the Player.", "win for the Computer."}
    return descriptions[result];
}

You can then make your printout much simpler:

void print_outcome(hand player, hand computer)
{
    printf("The player chose %s", get_hand_name(player));
    printf("The computer chose %s", get_hand_name(computer);
    printf("This match is a %s", get_result_description(get_result(player, computer)));
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Sadly, my earlier recommendation is as kind a response as I can make; it really is terrible for any professor to be forcing their students to use something as long outdated as Turbo C++, and students shouldn't put up with it. However, seeing how you are stuck in this position, I can give you some practical advice about getting your program to work.

The first thing I recommend is to break the input() function into several smaller functions; right now, there is a tremendous amount of redundancy in the code that could be simplified by modularizing the program better. For example, you could have a function that takes the outcome of the turn and prints whether it is win, lose or draw.

Second, you can structure the program better if, when testing a single variable's value for multiple outcomes, you used a switch statement instead of a series of if statements. This makes the intention clearer, and makes certain kinds of errors less likely.

You can also clarify things by naming the different types of casts, rather than using the magic numbers directly as you are doing now. You can use #define for this purpose, but since there are a sequence of values, you would be better off using enum types for this:

enum outcome {DRAW, PLAYER_WIN, COMPUTER_WIN};
enum hand {ROCK, PAPER, SCISSORS};

These can then be used like so:

outcome get_result(hand player, hand computer) 
{
    switch(player)
    {
        case ROCK:
            switch(computer)
            {
                case ROCK:
                     return …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

JasonHippy: This is actually a subtle point, and one that need to be understood: arrays are not pointers, but when used in certain ways will automatically be 'devolved' to pointers (cast, basically) by the compiler so that they can be treated interchangeably with pointers. The array variable name is still a name for the block of memory; there is no separate pointer value pointing to the memory block. The interchangability of arrays and pointers is syntactic sugar, not a reflection of the actual layout in memory.

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

Well, the first thing to look at is the headers, both the names and the format of them. A C program will have headers in the form of foo.h, whereas in (modern) C++, the standard library headers will be foo without the extension. Now, this isn't a foolproof method, as there's a lot of pre-standard C++ code floating around, but if you see a header without an extension, it is presumably C++.

Also, in C++, the C library headers should be prepended with a c, making (for example) <stdio.h> into <cstdio>. Again, a lot of older code doesn't match this standard, and even some current code isn't correct in this regard, but if it is like that, it is definitely C++ rather than C.

Next, the headers used may be different; C++ adds a large number of new libraries which use the C++ facilities that don't exist in C. The main ones to look for are <iostream>, <fstream>, <string>, <vector> and <algorithm>.

Fourth, C++ has namespaces, but C does not; so, if you see a reference to using namespace foo;, it will be C++. The same goes for the scoping operator, ::, which is used to indicate membership in either a class or a namespace.

Finally, if it uses cin and cout for input and output, it is going to be C++.

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

Well, to begin with, this is a C++ program, not a C program, and a poorly written one at that. The header formats indicate that it probably dates back to the late 1990s, when the then-new C++ standard was still being formalized - either that, or the programmer didn't understand the standard correctly. Several critical values are hard-coded in rather than parameterized, making the implementation brittle. The choice of bubblesort for the sorting algorithm is questionable at best, though with the small range it probably isn't very performance-critical. Finally, the code is pretty badly mangled, with the return types running into the function names and so forth, which means that without many fixes it wouldn't compile cleanly.

While it could fairly easily be re-written in C, you would be a lot better off writing a new implementation of the algorithm yourself. You would waste more time trying to fix this than you would starting over from scratch.

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

I am going to give you the same advice I give all the students who come here whose professors' are requring them to use Turbo C++ for current-day coursework:

  • Stand up in class, explain to your fellow students that the professor is teaching out-of-date and useless information that will hinder your ability to work in programming in the future,
  • Walk out of the course and encourage as many other classmates as you can to do so as well,
  • Go to the Dean's office and petition for the professor to be removed on the grounds of incompetence.

There is absolutely no justification for using Turbo C++ in an era when it won't even run on most new systems. Modern, powerful and effective compilers and IDEs which support modern versions of the language and present-day programming techniques are freely available from multiple sources, including Microsoft. To still be using and teaching a compiler that is older than most of the students using it is nothing short of criminal.

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

Consider a forum meant to assist programmers in learning to program, but whose members are constantly bombarded with requests from students who want their homework done for them with no effort on their own part. Explain why it is counterproductive to both the members and the students for the members to acquiesce to such requests, or conversely, provide some proof (e.g., partial code for the project) that the student has made their own effort on the assignment and is legitimately seeking help rather than a hand-out. Extra credit: Demonstrate the likelihood of being caught at cheating by the professor's TA, just from doing a script-driven Google search on fragments of the submitted code from each student.

ddanbe commented: Original :) +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, just to be pedantic about it, Dev-C++ and Eclipse are not themselves compilers; they are development environments which call (presumably) the GCC compiler (which to be even more pedantic, is not actually a compiler either, just a driver for the compiler and linker). I know it sounds picayune to make such distinctions, but there's a reason I bring it up.

You see, development of the original Bloodshed Dev-C++ stopped about ten years ago, and as a result, the IDE (and the default compiler) is sort of frozen in time from around 2005. As a result, the many refinements and changes that have been made to GCC have not been added to it, and compiler that it defaults to is now quite out of date.

However, if you are using Eclipse (or the Orwell Dev-C++ fork, or Code::Blocks, or any other up-to-date IDE), you'll have the latest version of GCC bundled with (as of when you installed it, at least), with the latest and greatest default settings, many of which have to do with code validation. Furthermore, each IDE will have different default switches set when they call GCC, including in most cases -Wall (show all warnings), which Bloodshed Dev-C++ didn't set by default. So, if you are using a newer version of GCC, with a different set of switches set, you could end up with some surprises when compiling code that had seemed fine in the past.

Specifically, the checking for function prototypes has …

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

Certainly. As I said, I use git for most of my SCM these days, so I'd recommend that, though I am aware that (like all software systems) it has its flaws. Others might recommend something different, like Mercurial or Bazaar, but I'll go with what I know for now. I'll also recommend GitHub for your offsite repo, for much the same reason. The GitHub user docs cover all of this quite well, but I'll go over it briefly for you now; I recommend you read through it, and the linked docs, at least once in toto before you go ahead with anything.

The first step is to make sure you have a suitable SSH public and private key pair. Chances are you already have done this for other things, but if you need to do it now, then what you need to do is run ssh-keygen and enter a suitable passphrase, one which you will remember yourself but which others are unlikely to guess at. Unlike most passwords, the pass phrase can have spaces in it. It can and should be fairly long, at least five or six actual words. You would then run ssh-add /path/to/your/key to register the key. The GitHub documentation on SSH keys gives more detail about how this should be done.

Nex you need to get the git software, whivch fortunately isn't a major dificulty on most Linux distros. From what you said earlier, I assume you are using a Debian based …