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

A forum is just a central meeting place, or (in this case) a place where you can talk with others about some topic. More specifically, it is a synonym for "message board".

In other words, you are already using the forum.

The link Dani gave should help you with this specific forum (Daniweb).

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

If I might recommend a bit of an improvement:

void ShowCardP1(int cardP1, string cardName[], string p_code[], string type[], string plusMode, string system[]) {
    cout<< "Product code: " << p_code[cardP1] << "  " << endl;
    cout<< cardName[cardP1] << "  " << endl ;
    cout<< "Type: " << type[cardP1] << "  " << endl;
    cout<< "PlusMode:" << plusMode[cardP1] << endl;
    cout<< "System: " << system[cardP1] << endl;
}

Mind you, if it weren't for the (rather absurd) instructions to use parallel arrays, I would instead declare a struct type to hold this information:

struct CardDetails {
    string name, code, type, mode, system;
} cards[SIZE] = {{"Abyss Devolos", "F0647", "Balance", "NA", "SpeedStorm"},
                 {"Ace Dragon", "E7609", "Attack", "NA", "HyperSphere"},
                 // ... etc. 
                };

// ...

void ShowCardP1(int cardP1, string cards[]) {
    cout<< "Product code: " << cards.code[cardP1] << endl;
    cout<< cards.name[cardP1] << endl ;
    cout<< "Type: " << cards.type[cardP1] << endl;
    cout<< "PlusMode:" << cards.mode[cardP1] << endl;
    cout<< "System: " << cards.system[cardP1] << endl;
}

This is probably a bit ahead of where your course is right now, however.

isyae commented: aaaa thankyouuu sooo muschhhh +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Uhm, 'struggle'? I have no idea what that refers to in this context. OTOH, void just means a function doesn't return a value, or conversely, that a pointer doesn't have a type.

Mind you, I don't think this code would even compile under most compilers today, or at least would give few warnings about it. The main() function must - I repeat, must - be declared as int in C++, and return some sort of value, no ifs, ands, or buts. Furthermore, <string.h> was renamed to just <string> in 1998, and most modern compilers won't allow that header - or if they do, they assume you want the C string library (renamed to <cstring> in modern C++, but still sometimes used in older code) rather than the C++ string class library. If you don't mind me asking, what compiler are you using?

Getting to the problem at hand, I would suggest that you have separate wincount variables for each of the teams; as it is, you are just counting how many games were played (except in the cases of ties). The simplest way to do this would be to declare two variables, wincount1 and wincount2, and use those to count the wins for the individual teams, rather than the aggregate of both.

    cout << "\tTeam " << team2 << " Points: ";
    cin >> p2;
    cout << "================================\n";

        if (p1 > p2)
            {
                cout << "Winner: Team " << team1 << endl;
                wincount1 += 1;
            }
        else if (p1 …
rproffitt commented: +1 for the win. +16
Jash_1 commented: It worked! I've derived some codes and it finally run. Thank you very much +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Not to be overly pedantic, but: .NET Framework is the library and runtime support system used by a number of different Microsoft languages. Visual Basic.NET is one language, C# is another, F# is yet another. The same .NET libraries work for all of them.

There may not be examples of how to use NAudio in VB.NET in the documentation, but it should be possible to do so with minimal effort. It is simply a matter of figuring out how to use the library classes and functions from VB.NET.

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

I would definitely try putting the "Days" constant string into a Label next to the ComboBox in question. As it is, you'd need to parse the string into the part with the numerical value, and the part with the "Days" substring, and you would need to do it any time you want the numeric value. It can be done, but it isn't really worth the effort, and in any case the Label would probably be clearer for the user.

Not to be too much of a nuisance about it, but it might help if we knew more about the program as a whole, in case there might be a better solution which isn't obvious just from this one small piece of the puzzle.

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

Just as an aside, since you know that it is in the range 0..30, have you considered declaring value as Byte (and casting the string using CByte()) ? That would at least help eliminate one possible source of error (since you would never get a negative value).

Perhaps try writing a utility function to force saturation, like this (warning, untested code, it has been a while since I coded in VB.Net):

Public Function CByte_Saturate_Range(data As String, min As Byte, max As Byte) As Byte
    Dim value As Byte
    Dim swap As Byte

    If min = max Then
        Return min
    End If

    If min > max Then
        swap = min
        min = max 
        max = swap
    End If
     ' convert to a Short first, then force it to a positive absolute value
     ' before converting it to Byte
    value = CByte(Math.Abs(CShort(data))
    If min > value Then
         value = min
    ElseIf value > max Then
         value = max
    End If
    Return value
End Function

You would call it like so:

    value = CByte_Saturate_Range(Label10.Text, 0, 30)
    If value > 0 Then
        value = value - 1
    Else
        Form11.Button5.PerformClick()
        Timer1.Stop()
    End If
    label10.Text = CStr(value)

While this might seem overkill, it would at least separate the logic for converting and saturating the value from that of testing for the timer value.

Actually, let me back up a bit before I finish: why is the timer based on a Label's value in the first place? That might help us understand the wider goal involved.

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

I can't say if it the main source of the problem, but the line If value >= 0 Then has the test reversed; it should be If value <= 0 Then instead.

This doesn't explain why it fails at exactly zero, but you'd be better off correcting it anyway.

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

What exactly are you taking the average of - the rows, the columns, or all of the values together?

Zerrin_1 commented: all of the values together, but I found the answer, thank you +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, I suspect that the opposite is the problem: the object was declared, but never initialized, and thus has a value of Nothing.

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

You've checked the boot order in the BIOS, correct?
Speaking of which, since you mentioned that this is an older system: is it UEFI, or Legacy BIOS?
Also, how did you install Ubuntu originally (assuming it was installed already and that the error message is from the HDD boot)?
Did the error message include any other details beyond the message you already posted?

EDIT: Doing a quick search on the error message, it looks to be a Gnome error rather than a Linux one (which I was wondering about, it was far too casual a message for the Linux kernel). If so, it should be possible to use Ctl-Alt-F2 to get to a shell. You should be able to remove and reinstall Gnome itself in that case.

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

Overall, in Python (and nearly every other language) you generally want to use global variables as little as possible, and share variables between functions and methods by passing them as arguments. You can use globals, but you would be fighting the language's overall procedural/OOP design in doing so.

As a rule, you want to limit the scope of variables to the narrowest visbility that is usable, not the widest. Otherwise, you could end up with undesirable side effects where a change in a variable in one place causes its use elsewhere to be compromised. Ideally, when working on one function you don't need to pay any attention to the local variables in any other function - that's why they are local, you can't access them from anywhere outside of the local scope.

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

can i put my vars in a txt like this:

var1=something1
var2=something2

and access them from python?

Would it be acceptable to use a Python file with these as globals, and then import the data that way? It would leverage the Python package system to avoid having to explicitly read the data files. I don't know if this is something which would be feasible for your project, but it might be worth looking into.

razstec commented: the idea is to add remove change the content of the software without using the code, just fill the txt and your set for your needs +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think a more basic explanation may be called for...

Like most languages still in use, C++ is still evolving over time, and the official standards for the language is updated by the International Standards Organization (ISO) and the American National Standards Institute (ANSI) at irregular intervals as the development committees set the changes into the rules. The different versions of the language - which generally are backwards compatible with older code, but add new features and clarify the details of older rules - are given by the name of the agency that released it, the name of the language, and the year it was released. For example, ANSI C 89 was the first 'official' standard for C, released by ANSI in 1989. The current standard most C++ compilers support (at least partly) is ISO C++ 11; since ANSI accepts the ISO standards for most programming languages as the same as their own, the 'ISO' part is usually dropped, so it is called C++11. There is a newer update, C++14, but it is a minor update for the most part (mostly clarifications of problematic parts of C++11) and most C++ compiler developers haven't gotten to working on supporting it yet.

You'll also note that most C++ compilers are also C compilers, so you want to make sure that you are compiling for C++ for this class, not C.

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

Asking for help in an illegal activity is a violation of Daniweb forum rules, specifically:

Do not ask for help to pursue any illegal activity including, but not limited to, hacking and spamming

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

Again, I would need to see both the function you have written, and the error message you are getting, before I could have any hope of answering that question. Sorry to harp on this again and again, but you need to give us all the information needed to understand what is going on with your program.

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

OK, first off, you are never setting the value of ans, so ans is by default zero. Any answer other than 0 will fail.

As for why it never gets to the esle part, the answer is simple: you have dupicated the if() condition one successive lines. Correctly indented, it looks like this:

         if(num2 == ans)
            if(num2 == ans) {
                System.out.println("answer correct, excellent!!!");
                int numtries = 1;
                scores = 10;
            }
            else {
                System.out.println("incorrect, \n try again");
                count++;
                scores -= 5;
            }

The effect of this is that the first if() always is false, so the second if() - which is the one with the else clause - is never executed.

This would have been clear if you had indented the code in a consistent fashion. While which indent style you apply is your choice, consistency in indenting isn't optional. You might want to see if the editor or IDE your using has an auto-indent function, and see if that helps. BTW, just out of curiosity, which editor are you using? Someone here may know if it has such a feature, if you aren't sure yourself.

I would add that you're going about this the wrong way - it is clear you have misunderstood the assignment. The goal isn't to have the user guess the numbers, but to put them in order. What you need to do is show them the numbers in the order they were generated, then ask them to repeat them in …

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

sigh I need you to paste the exact error message into a post so we can see it.

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

We still would need to know what the syntax error is, not just where it is occurring.

As for the second part, you are setting array_size to zero here:

int array_size =0;

Then you are comparing i < array_size. If i is set to zero, it isn't less than zero, is it?

You want to set array_size to the total size of the array. So, if the array is meant to have five elements, you would set

int array_size = 5;

That's the size of the array, not the index of it. The whle idea is that you are counting up to 4 (which is the highest integer below 5, naturally), so array_size indicates the endpoint of the loop iteration. Mind you, you want to declare array_size as final (that is to say, constant), and use it when you construct the array:

final int array_size = 5;

int[] rand_array = new int[array_size];

This gives you a fixed, named value for the array size, so that if you ever need to change it, you only need to change it in one place.

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

Can you post the error messages you are getting, please?

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

decorators only work on function call, not on definition

Actually, they can be either one, sort of; the decorator syntax is just syntactic sugar for calling the decorator function with the defined function as its first argument. That decorator function can be any higher-order function that takes a function as its first positional parameter, and returns a function as its only return value.

Defining a decorator operation that is invoked at function call requires wrapping the defined function in a closure, and returning the closure as the value of the decorator, but the decorator itself runs at define time.

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

basically, what I want to do is add a function name to an outside reference in a safe sys.modules reference without copying the name...

Have you considered writing a decorator? Perhaps something like so:

@register
def myfunc(args):
    x = None
    return x

You could even set it up to allow multiple registries:

@register(myFunctionRegistry)
def myfunc(args):
    x = None
    return x

I'm not quite sure how you would implement it, but that seems like the most reasonable approach to take, given the semantics you want.

Gribouillis commented: Of course +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

How am I supposed to accomplish this. How can you create an arrays that could store arrays so that it can compare random numbers

If I am reading this correctly, what you are looking to do is have two arrays - one holding the random numbers, the other holding the user input - and compare the results from each, correct? Well, the first step would be to declare an array (obviously), and populate it with the random values:

    final int MAX_SIZE = 5;

    int[] rand_array = int[ARRAY_SIZE];

    for(int i = 0; i < ARRAY_SIZE; i++) {
            rand_array[i] = (int)Math.random() % 16;
    }

Note that the first element of an array is element zero - an array of 5 elements would go from rand_array[0] through rand_array[4]. Thus, you should be initializing i to zero, as I have above.

Also, I am pretty sure you meant to use modulo 16, not multiply by 15. Using modulo this way will limit the range of the random numbers to 0..15. It isn't the best way to do it - it tends to bias the values to the lower end of the range - but it should be adequate.

A better solution would be to use a Random object instead:

// declare this before the for() statement
Random randomizer = new Random();

for(int i = 0; i < ARRAY_SIZE; i++) {
    rand_array[i] = randomizer.nextInt(MAX_RANGE);
}

Where MAX_RANGE is the maximum value in the range (15, in this case). …

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

Erk, I did it again - I was editing my post, adding details and clarifying some points, when you answered me. You may want to check what I added to it.

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

I keep getting an error for "password was not declared in this scope" in main.

As tinstaafl pointed out already, that is because password isn't declared in main(), and in any case you are using a C-string (a zero-delimited character array, as used in the C language, the predecessor of C++) instead of a string object (a class that is specific to C++, which is recommended when working with new code in C++, and what the assignment actually asks for). C-strings aren't so much a type as they are a convention for how to use a char array to hold strings; I'll explain what I mean by that a little bit later.

So, what you want to have is a declaration for a string in main(), which you would read in from the console in main() and then pass as the argument for IsValidPassword().

One of the principles of code design is the separation of concerns; that is, you want to have the code for communicating with the data source (e.g., a text shell, a windowed user interface, a database) separate from the code which processes the data (e.g., computations based on the data, validation tests, etc.). This makes the logic of both sections easier to understand, makes the sections more modular, makes the interfaces between the sections clearer, and makes it so the computation isn't bound tightly to the I/O. For example, if you write your validation function so that it only gets the data from its …

Slavi commented: wow .. +6
TObannion commented: Very explanatory and in depth. Thanks +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think you'll find that it was AH, and that you wanted to set that to 4Ch; however, since AH is the high byte of AX, using MOV AX, 4C00h is the same as assigning MOV AH, 4Ch followed by MOV AL, 00h. The effect is (almost) the same, since you were returning a zero to the shell anyway (zero is used by the shell to indicate a successful completion of the program), but this is misleading; for other interrupt calls, you will sometimes need to pass an argument through AL, and if you had set AX instead of AH, you'd have a serious problem. In this case, it works out (and even saves an instruction, technically speaking), but you should be aware of why it works, and what is really happening, in order to see the potential problems in that approach.

hefaz commented: Yeah +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think you misunderstood what stultuske was saying. What he means is that then you post to Daniweb,the code section and only the code section should be pasted into the message using the Code button, while the actually text of the message should be entered with the normal editing window.

Just to clarify the issue, Markdown (the format used by Daniweb) automatically puts anything indented by four or more spaces into a code sub-window. So, if the text is indented, it will show up as code, even if that isn't what you intended. So, when adding a section of plain text, always make sure that the text is not indented, but the code is.

So, for the code you posted, it should look like this:

        Scanner keyin = new Scanner (System.in);
        Random randobj = new Random();

        int user1age, user2age,count = 0;
        String user1name, user2name;
        int ans = 0, scores = 0;

        System.out.println("Hi Welcome Students!!!");
        System.out.println("To the school of counting numbers!!!!");
        System.out.println("This school will teach you how to count numbers");
        System.out.println("I am going to implement a game of counting but will need two players");
        System.out.println("Is there anyone who is interested");
        System.out.println("The rules of the game goes like this");
        System.out.println("The players must between the ages of 5 and 10");
        System.out.println("They must not be older or younger, the comprise of three attempt");
        System.out.println("Each players is given three chances to get the correct answer and if not the game goes to the second players");
        System.out.println("Do you students think that you are up …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, aside from the fact that 4C00 hex is far too large to fit in to fit into a byte (the maximum value for a single byte - that is to say, 8 bits - is FF hex, or 256 decimal), a quick check of Ralf Brown's Interrupt List's entry for interrupt vector 21h shows no parametric function for 4C00h. Are you sure you didn't want (INT 21h, AH=4Ch)[http://www.ctyme.com/intr/rb-2974.htm] (exit with a shell return value)? That would be the usual function to call at the end of a MS-DOS program, IIRC.

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

You'll have to give us a good deal more detail about the problem, I'm afraid. What kind of constant are you trying to use? I assume it is an integer, in which case you probably don't have many options - Turbo Assembler (which is the TASM I assume you mean - there were at least two others which went by that acronym) was a 16-bit real mode assembler for MS-DOS, and did not work directly with values greater than FFFF hex (65536 decimal). There are ways to work around this, but they aren't particularly easy.

Which leads to the next question: why TASM? is this for coursework (in which case you probably don't have any choice), and is there a reason why it is in an archaic 16-bit assembly dialect for MS-DOS? Current versions of Windows (Vista and later) won't even run 16-bit real mode programs except through an emulator such as DosBox; if you have any choice at all in the matter, I recommend that you ditch TASM for a modern assembler that actually still runs, such as NASM or FASM.

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

OK, rather than getting caught up in the details of the specific matter, let's talk basic principles for a bit.

The main purpose of inheritance is to allow common elements of two or more classes to be defined in a way that the child classes can share what is defined in the parent class. Let's say you have a class Vehicle, which defines - without regard to the mechanism - a method move(). Now, if you want a class Automobile that describes the properties and behaviors of a car, you need not define an entirely new class; you can inherit most of what you need from Vehicle, including the move() method. You can override the existing move() method or not, depending on how you want it to behave. You can also add new methods, such as brake(), to extend the abilities of an Automobile beyond those of the parent Vehicle class.

Now, here's the important part in regards to your question: since an Automobile is an instance of a Vehicle (given our definition of Automobile), you can have any Vehicle instance hold an Automobile as a kind of Vehicle. Because it is a Vehicle, any method that is common to all Vehicles can be applied to the variable, including move(), and it will correctly use the version of the method for the actual object's class. In other words, even though it is a Vehicle variable, since the object is an Automobile, it will use the move() for an Automobile, if …

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

I am guessing that you used the built-in float type for this, but given that you are dealing with currency, I would recommend using the decimal module for representing the monetary value instead, to get the best control over the significant decimal places, and applying locale.currency() to format the value as a string. While the links I posted are for the Python 3.4 docs, thhis should apply to Python 2.7 as well.

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

Before I get to my answers, let me ask you a question: what is your purpose in accessing dev/urandom? Is this for a class assignment, or part of a larger project? Is there a specific reason why the usual srand()/rand() functions aren't sufficient? What are your goals in doing this?

OK, now that that is out of the way, here goes. The first thing to know is that /dev/urandom (and the files in the /dev directory in general) isn't actually a file at all; it is a pseudo-device, a sort of handle for accessing the kernel pseudo-random number generator in this case.

To read either /dev/random or /dev/urandom, you need to read in a block of one or more bytes (type char is usually used, though using uint8_t might make it more easily understood that the buffer is being used for it's numeric value), which you would then pack into the integer either by using shifts, or by having the buffer as a union of two overlapping buffers:

#define INT_BUF 32 
#define BYTE_BUF (sizeof(int) * INT_BUF);

union 
{
    uint8_t buffer[BYTE_BUF];
    int rand_values[INT_BUF];
} random_buffer;

This StackOverflow thread explains how to read from /dev/urandom effectively, including why you might want to read several values at once. Note that in one of the later answers, it is explained that you ought to check to make sure that dev/urandom hasn't been spoofed to /dev/zero or something similar before reading from it.

The difference between dev/random and /dev/urandom is that …

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

respectfully you don't have any right to notify of which country I belong to and what are our professors teaching us?

I apologize for overstepping on this matter, then. Your location is posted in your member profile, but you are correct, it was inappropriate for me to point it out.

As for what your professors are teaching, that was meant as a warning to you that what you are being taught is at least partially invalid, and to be aware that your coursework is likely to give you little traction in modern programming.

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

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

As for compound data structures, I can see that you haven't covered them, which means that it probably means that you aren't free to use them for this project; however, I can explain them ahead of time for you so you will have a bit of a leg up when you do cover them.

In C++, struct and class are basically the same, except for the visibility of the members; however, structs are usually used for POD (Plain Old Data, that is, member variables but not member functions). For this reason, I'll cover structs first, then shift to classes afterwards.

A struct basically is a name for a group of related variables. Unlike an array, which is homogeneous (that is, every element is the same type) and indexed (i.e., the elements are referred to by number rather than name), a struct's member variables are named, and can be of different types. For your particular case, you would probably want to define a Point2D type, and then use that to define a Line2D type.

struct Point2D
{
   double x, y;
};

struct LineSegment2D
{
    Point2D start, end;
};

The member variables can be accessed using the member reference operator (or dot operator, .), like so:

LineSegment2D line_1;
line_1.start.x = 2.0;
line_1.start.y = 1.1;
line_1.end.x = 4.5;
line_1.end.y = 3.8;

How you could apply this to re-writing your functions might go like so:

LineSegment2D* getLineSegment() //Reference function
{
    LineSegment2D* line = new LineSegment2D();

    cout << "Enter x-y …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

By explict function, all I mean is a function which explicitly returns a value. For example:

int foo(int bar)
{
    return 23 * bar;
}

which would be used like so:

int quux;

quux = foo(17);    // quux now assigned the value 23 * 17 == 391

It is related to why most procedural sub-routines are referred to as 'functions' in the first place: a function with a return value is conceptually and semantically similar to a mathematical function (though they aren't strictly the same thing; a mathematical function defines a relationship between its domain and its co-domain, while a C++ function defines a computation that returns a value).

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

There should not be a '.cpp' extension on the header file, just '.h'.

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

The error is a very simple one: you misspelled the header name in your program source file. Just change the 'g' to an 'e' and it should go through correctly.

BTW, I would do four other things. First, I would remove the using namespace std; from the header file, and explicitly scope the standard library functions and objects using std::, like so:

std::cout << "The area of the Circle is " << S << std::endl;

Otherwise, the using directive carries over to every file that includes that header, which causes an effect called 'namespace pollution', where you start to get conflicts between the names of functions and classes. The whole purpose of namespaces is to help avoid naming collisions, and unrestricted use of the using directive undermines that. It is OK to use using namespace std; in the main program itself, as it won't leak out to any other parts of the program, but having it in a header or a class implementation file is definitely a Bad Thing.

Second, I would add #include guards to your header file, to protect it from being included more than once.

#ifndef FIRSTHOMEWORK_H
#define FIRSTHOMEWORK_H 1

#include <iostream>

class Circle 
{
// the rest of your header goes here
// ...

};  // end of class Rectangle 

#endif

It isn't really that important for this instance, but it is a good habit to get into.

Third, I would move the actual methods of the three classes to …

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

Sandro_1: If you don't mind me asking, what is it you are trying to accomplish? I'd guess you were calculating the median of the data set, but you didn't specify that the ArrayList was sorted; if it isn't, then it is hard to see what you would be getting from it. What is the purpose of this?

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

Wouldn't make sense to have the class implement Serializable rather than hard-coding the file output? I haven't used Java serialization before, so I don't know the limitations and weaknesses of it, but I would expect that using that would save a good deal of effort and make the code less brittle.

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

Ah, I didn't realize that was an actual requirement of the assignment. Sorry.

One thing I will strongly recommend is reorganizing the program into functions, so that it is easier to read, and less redundant. Here is what I came up with (though it doesn't take into account the spaces issue):

from random import randint
from statistics import mean

def generate_key():
    """ generate a key for the enciphered message"""
    numbers = list()
    # while n is less than 8
    for n in range(8):
        # generate eight random numbers between 33 and 126
        partial_seed = randint(33, 126)
        numbers.append(partial_seed)
        # this averages and rounds the values in numbers
        # and then subtracts 32
        avg = round(mean(numbers))
        return avg - 32

def apply_cipher(plaintext, cipher_key):
    return [(ord(chars) ^ cipher_key) for chars in plaintext]

def apply_deciphering(ciphertext, cipher_key):
    plaindata =  [chr(values ^ cipher_key) for values in ciphertext]
    return ''.join(plaindata)

def encrypt(source, dest):
    """ encrypt the given file """
    cipher_key = generate_key()
    with open(source) as plaintext_file:
        with open(dest, "wb") as ciphertext_file:
            ciphertext_file.write(bytes(chr(cipher_key), 'utf-8'))
            ciphertext = apply_cipher(plaintext_file.read(), cipher_key)
            ciphertext_file.write(bytes(ciphertext))

def decrypt(source, dest):
    with open(source, "rb") as ciphertext_file:
        ciphertext = ciphertext_file.read()
        cipher_key = ciphertext[0]
        plaintext = apply_deciphering(ciphertext[1:], cipher_key)
        with open(dest, "w") as plaintext_file:
            plaintext_file.write(plaintext)


def print_menu():
    menu = ['Display main menu', 'Encrypt Message', 'Decrypt Message', 'Exit program']
    for opt_number, option in enumerate(menu):
        print('{0}) {1}'.format(opt_number, option))

if __name__ == "__main__":
    print("Hi, Welcome to Text Encryption")
    print("This program will encrypt or decrypt a text file chosen by you.")
    print_menu()

    #the user only has 4 choices
    menu_choice = 0

    #menu_choice == …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I don't think you actually would want to treat the spaces (or whitespace in general) any differently from the other plaintext, actually; you want to write the ciphertext out in a form that gives as little information as possible to a cryptanalyst, so enciphering the whitespace would make more sense. You don't want to store or write the ciphertext out as a string at all, but as a binary in your cipher.

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

Before making any suggestions, I would like to ask if your course of study (whether personal or formal) has gotten to functions and how to write them yet. This would be a big factor in how you approach thsis matter.

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

Ah, a good question, and one I am actually glad to see here. It shows some thought beyond the usual questions here.

However, I should caution you that thater are a lot of ways to approach this issue, and which is going to work for you will depemnd on both your own temperment, your experience, the scope and nature of the project, and who well established the conventional solutions to the problem(s) are. You generally will approach a small project different from a larger one - or rather, you generally want to do as much as you can to break larger ones down into smaller ones, then apply the design principles to the individual parts.

One thing I will say is that your approach will evolve over time, as you become more fluent in the programming languages and techniques. Just as when you arew learning a spoken language, and often have to rely on phrasebooks and dictionaries to get your through until you start to actually grasp the language, so too will you need to work a lot with references and tutorials at first. The difference is that this is a wide-open field, and one that changes rapidly, so chances are there will always be things that will send you looking for reference material no matter how skilled you become.

Not knowing what you're skill level is, let's start with the simplest suggestions first:

  1. Try to get familiar with as many of the common data structures, algorithms, and design patterns …

mike_2000_17 commented: Nice! +14