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

Actually, there's still a problem with it; the formatting string is incorrect, which means that the time string never gets created. The correct format should be "%I" for hours (12-hour format) and "%M" for minutes.

Try the following:

#include <iostream>
#include <cstdio>
#include <ctime>

using namespace std;

const int Buffer_Size = 32;

int main()
{
    time_t rawtime;
    struct tm * timeinfo;
    char space[Buffer_Size];
    time (&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(space, Buffer_Size,"Current Time: %I:%M %p",timeinfo);
    cout << space << endl;
    return 0;
}
Ancient Dragon commented: good catch :) +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you tell us more about what you've tried already?

I know that it isn't C, but you might want to look at the circuit simulation code in Chapter 3 of Structure and Interpretation of Computer Programs. It goes into detail about how the circuit connections can be implemented, and while you probably won't find the techniques they use immediately helpful, it could provide some insights into the problem.

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

While I have only looked at this briefly, I can tell you that the main problem stems from this error here:

main.c|75|warning: implicit declaration of function 'get_endereco'|

What this means is that you haven't declared the function get_endereco() at that point of the source file yet, and the compiler can only guess what the return type f the function is. By default, the return type of an undeclared function is assumed to be int, hence the errors immediately following this one:

main.c|75|warning: assignment makes pointer from integer without a cast|
main.c|76|warning: assignment makes pointer from integer without a cast|

The error that comes up after that occurs when you finally do reach the implementation for get_endereco(); because the compiler has already generated a default function return prototype for the function, it gets confused when it then sees the real function return type:

main.c|122|error: conflicting types for 'get_endereco'|

The solution for this (and possibly for several other problems) is to add a function prototype before the functions that call get_endereco(). I would in fact recommend adding prototypes for all of the functions (except main(), which has a pre-defined type), just to ensure that the return types and parameters are correctly known to the compiler beforehand:

void get_equipas(equipa_cabecalho* ponteiro);
void get_jogos(jogo_cabecalho* ponteiro,equipa_cabecalho* ponteiro2);
void cria_lista_equipa(equipa_cabecalho** ponteiro);
void imprime_equipas(equipa_cabecalho * ponteiro);
void cria_lista_jogos(jogo_cabecalho** ponteiro);
Equipa * get_endereco(equipa_cabecalho* ponteiro,char (*nome));
void add_jogo(jogo_cabecalho* ponteiro,equipa_cabecalho *ponteiro2,char eq1,char eq2,int eq1res,int eq2res,int dia,int mes,int ano);
void menu();

This is …

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

In the absence of the necesary information from the OP, I can only make broad suggestions, with the number one recommendation being to replace all of these repetitive tests with a table and simple loop.

struct Q_and_A 
{
    std::string question;
    std::string options[3];
    char answer;
    int points;
};

Q_and_A exam[] = {
    {"What is called 'THE HOLY LAND'?", {"Jerusalem", "Mathura", "Mecca"}, 'a', 10},
    {"What is called 'THE ROOF OF THE WORLD'?", {"Nepal", "Rome", "Tibet"}, 'c', 10},
    // and so on ...
    {"What is called 'THE DARK CONTINENT'?", {"Asia", "Australia", "Africa"}, 'c', 10}
};

// later, in the program code...

for (int i = 0; i < 10; i++)
{
     char answer;

     std::cout << std::endl << "Q" << i <<". " << exam[i].question << std::endl;
     for (int j = 0; j < 3; j++)
     {
         std::cout << ('a' + (char) j) << ". " << exam[i].option[j] << std::endl;   
     }
     cin >> answer;
     if (answer = exam[i].answer)
     {
         x += exam[i].points;
         std::cout << "\nGood Job.";
         std::cout<<"\n Your score is " << x << std::endl;
     }
     else
     {
         std::cout << "\n Sorry wrong answer." << std::endl;
     }
}

I don't know if this solves the problem you were posting about, but I'll bet it solves a lot more than just that.

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

Ah, I see. If arrays and functions present a problem for you, this may be a bit difficult.

I will say that it's clear you have worked with arrays already, even if you don't know them as such. An array is a variable that holds a group of values of the same type, rather than just the one value normally found in a variable. An array in C is declared like these below:

char my_array[10];
struct student classe[20];
struct Bank banks[2];

you then access a given value inside of an array like so:

my_array[0] = 'H';
classe[5].name = "John Doe";

You may know these by some other name in Portuguese, or by the alternate Enlgish names 'vector' or 'table'. You'll also note that a string in C is nothing more than a char array that ends in a null character ('\0').

Functions may be another story; if you haven't learned about them yet, it may be that I'd be jumping ahead of your coursework if I explained them to you now. Still, a bit of preview may not hurt, so here goes. A function is a separate part of a program, which can be called from some other part of the program to perform a task or compute a value. Functions usually take some kind of values in as arguments, and usually return a result.

You have already been using functions which are part of the standard library, such as printf() and system(). These are usually …

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

In the main() function, you have bank1 and bank2 declared as type char. This would mean that they are each one character long; that isn't really enough to accomplish what you are trying to do with them. Rather than that, I would recommend using the structure types I've already suggested.

    struct Bank banks[2];

By using an array, you then have a logical relationship between the two values, as well.

Now, when reading in the values, you want to read the bank ID seperately from the manager's name; since one is an unsigned int and the other is a char array, trying to read them both together won't work. I'd recommend writing a small function for this purpose, as you have to be able to do it for both of the banks in question separately.

void readBank(struct Bank banks[])
{
    char buffer[BUFFER_SIZE];
    unsigned int branch;
    static unsigned short count = 0; /* track how many branches have already been read in */

    /* sanity check - do we already have two banks set up? */
    if (count >= 2)
    {
        printf("You already have two banks set up.");
        return;
    }

    printf("Enter a branch ID number for the %s branch: ", (count == 0 ? "first" : "second"));
    fgets(buffer, BUFFER_SIZE, stdin); 
    sscanf(buffer, "%u", &branch);
    banks[count].branch_number = branch;

    printf("Enter the branch manager's name: ");
    fgets(buffer, BUFFER_SIZE, stdin);
    strncpy(buffer, banks[count].manager, BUFFER_SIZE);

    count++;  /* increment count so that we know how many banks already exist */
}

You should add #include …

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

lucaciandrew: I have to disagree with you on this - the fully qualified std::string is generally preferable to using namespace std;, especially inside headers. Headers get included in multiple locations, some of which could present namespace collisions if you have the std namespace (or any other, for that matter) used in them will-nilly, and when the collision occurs because of a header, it can cause bugs that are especially hard to track down. It goes against the entire purpose of having discrete namespaces to then turn around and have a blanket using on them everywhere you have a need for something within them.

The same applies to headers; you actually want to limit the number of headers you #include within other headers, as any client programmer who then uses that header may be unaware of all the things the header adds to their code.

As a rule, you want to restrict the visibility of exernal code, not broaden it.

BTW, <stdlib.h> and <ctype.h> are the C forms of the headers; in C++ one should always use <cstdlib> and <cctype> instead. As for <cctype.h>, there is no such thing; I assume that you either got confused, or it was a typo.

I hope you take these critiques in the spirit they were intended.

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

OK, what problem are you having? The code your instructor provides is pretty straightforward (if a bit BFI, presumably on purpose) and should be easy to extend. Where is the issue, and what is it doing wrong?

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

Looking at this page in MSDN I believe you want to use either Convert::ToString(makebreak) or the equivalent Int32::ToString(makebreak).

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

Why 128 characters for the name? Call it a habit of mine; if I am using an arbitrary size for something, I usually use a power of 2 rather than a power of ten. The reasoning behind this is a bit obscure, being related to the Zero-One-Infinity Rule, but basically the idea is that powers of two 'fit' better for many programming purposes than powers of ten, and if nothing else look less obviously arbitrary.

As for why five characters for the account numbers, if you look at the problem statment again, that's how many are required. The first two characters hold the type of the account, as given in the problem statement.

From what you said, I gather that 'include' here is meant in the sense of 'add'. That explains a good deal, as I was wondering how account creation was supposed to go.

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

OK, I'll start by making three points. First, it is a good idea to always give an explicit return type for all functions, especially main(), which must by of type int if you are to write portable code. Second, while it is a common mistake, you should never apply fflush() to any input stream, including stdin. Finally, you generally want to avoid using the system() function for screen management, as explained here and here.

Having said that, I will turn to the actual issues with your code.

The Bank structure should really be the key one here, and I think you need to give it some more work. At the very least, you'll want to have both the name or identifier for the bank branch itself, and the name of the bank manager.

struct Bank
{
    unsigned int branch_number;
    char manager[128];
};

You then want a struct type for the bank accounts, which will hold an account number, and an account balance.

struct Account
{
    char account_number[5];
    int balance;
 };

You'll also want another struct type for the bank customers, which would have the customer's name, a customer ID number, and an array of three Accounts. You'll then want an array of 100 bank customers to hold all the possible accounts.

struct Customer
{
    char name[128];
    unsigned int id;
    struct Account accounts[3];
} customers[100];

As for the operations you're supposed to have, the wording of the problem is …

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

Where are you inserting the new strings to? If you are trying to insert them into the existing String variable, that won't work; you would end up overwriting the part of the string you are putting it into, and possibly (if the insertion point is close to the end of the string) overrunning the end of the string.

So what do you need to do? Well, that depends on what you're going to do with the string after you have inserted the string values into it. If this is going to be local to MyFun(), then you can simply declare a large-ish buffer, and copy the part of the original string you want to keep into the buffer, interleaved with the new data you are adding to it. OTOH, if you want to return or pass back a copy of the new string, well, you will still want to have a large static buffer local to the function, but once you've finished processing the old string, you'd get the length of the final string using strlen(), and allocate a suitable char array that you can then copy the string into, and return that.

I suspect that we're not getting the full picture, here. This program has the feeling of a test program, something intended to help you work out how to do something for some larger program later on. What is your final goal with this?

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

Actually, I wouldn't expect it to execute in this case; that was mostly a bit of defensive programming, in case you later had a much larger data string to process which happened to have more than (in this case) 16 occurences of the 123 code. If you change the value of array_size in main() to, say, 2, you'll see what it does when it goes over the size of the current block.

In the existing code, the block size is 16, whereas the string you are using right now only has 4 instances of the 123 code you are looking for. So, why use such a large block size, if you don't need it? Because you don't want to reallocate very often, and if possible, you want to avoid it completely. With the four occurences in your existing string, it shouldn't ever reallocate the memory; but having the test and reallocation code there is a good practice, as you may end up re-using this code on a larger dataset, and then have to worry about resetting the size manually, etc. It is better, IMAO, to take care of it up front, just to be safe, while at the same time avoiding having far too large a starting block size.

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

The reasons why it is crashing is quite simple: first off, you are only allocating one structure's worth of memory in your call to calloc(). When you try to access the (non-existent) second structure, you run off the end of the allocated array, causing a memory protection violation. My recommendation is to keep track of the size of the allocated array, and pass it as an argument to MyFun(). This way, you can tell how larger the array is, and even reallocated if need be.

Second, the way you are passing the array of _MyStruct is wrong. Right now, you are declaring the argument as an array of _MyStruct pointers, which is not what you are allocating. You want to pass it as an array of _MyStruct, nothing more. This also means that you want to use the member notation (dot notation) to access the elements of MyStruct, rather than member indirection notation (-> notation).

My version of your code comes out to be:

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

struct _MyStruct
{
    char Mycode[10];
    int Index;
};

unsigned int MyFun(char *String, struct _MyStruct MyStruct[], unsigned int MyStructSize );


unsigned int MyFun(char *String, struct _MyStruct MyStruct[], unsigned int MyStructSize )
{
    unsigned int i = 0, j = 0, code = 0, codecount = 0, array_size = MyStructSize;

    for (i = 0, j = 0; i < strlen(String); i++, j++)
    {
        if((String[i] == '1') && (String[i+1] == '2'))
        {
            /* store the starting index of 123$ code */
            MyStruct[codecount].Index …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While the point about your code was broadly speaking correct, the explanation given is a bit off. It isn't so much how the pointer was declared or assigned as much as it is about how the memory it points to was allocated, and how long you need that memory to stick around.

The first thing you need to know is that in a program, there are four different ways memory can be allocated to the program. The first is read-only memory, which is where things like constants and string literals are stored; on modern systems, trying to change something in read-only memory will result in a protection fault. The next kind of memory is global memory, where global variables are set up. This is a fixed amount of space given to the program when it starts, and cannot be increased or decreased.

The third kind of memory is local memory, which is automatically allocated when a function begins and deallocated when it returns. While there are a few different ways that this could be implemented, it is almost invariably done using a stack, a data structure so ubiquitous that all but a handful of computers these days have built-in hardware support for it. A detailed explanation of how allocating memory on the stack works can be found here, but the details aren't terribly relevant right now. Suffice it to say, you can have a pointer to any of these three types of memory, but you should …

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

I think eveyone here would be willing to help, if you could show that you've made some effort with it yourself. I realize that your circumstances are hard, and I am willing to accept that you need help; but we still need to know that you are sincere in your intentions.

What all this means, practically speaking is: show us the code. It doesn't matter how incomplete or broken it is, so long as it shows that you have made a genuine effort to solve the problem. That, plus a thoughtful explanation of what it is supposed to be doing and what is going wrong, is all we really ask of you.

Please, whatever you do, don't just give up and walk away from here. We will help you, but you have to show your work first. Be patient and considerate to us, and we will show you the same courtesy.

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.

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

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

Ezzaral commented: Agreed. +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It's very unlikely that the characters are going to appear as you want them to, for a console application. You would need a code page which has the appropriate glyphs, mapped to the correct Unicode code points.

While there are Unicode code pages for UTF-7, UTF-8, and UTF-16, I don't know if any of those include the chess characters. I find it unlikely that they do, to be honest. Even if one of them does, the limitations of the console fonts mean that the glyphs are probably going to be virtually unreadable.

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

Setting aside the encryption code for the moment, I took a look at the sound card code, and found something potentially problematic. The program as written uses /dev/dsp, which is the OSS sound device; but most modern Linux distros use ALSA for sound support, and not all of them have backwards compatibility support for OSS (my own Linux partition, which runs the current version of Gentoo x86-64, does not, for example). While it is generally possible to install the OOS compatibility library, it doesn't change the fact that you're using an outdated system for your sound access.

LotusDream: You may want to start over learning the ALSA library, which if nothing else is a lot more complete than the OSS sound support.

On a related note, you are reading in and outputting raw sound data from the sound card. I'm not sure that the data you're collecting would work on other models of sound cards than the one you are using yourself. I may be mistaken about this, but in any case, you probably want to convert the sound data to a compressed format before sending it anywhere, as WAV sound data tends to be rather large.

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

I am beginniong to suspect that the problwem lies with my randomization function. Is there some bias in it that I am not seeing?

/* generate a 64-bit unsigned random number */
uint64_t rand_u64()
{
return ((uint64_t) rand() + (((uint64_t) rand()) << 32));
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you please tell us what you need help with? Aside from indent style issues, I mean.

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

At the risk of completely highjacking this thread, I have been working on getting my own version of this code going, and have had a certain amount of success. However, I wanted to change the key generation to use generated primes based on a passphrase, rather than the constant primes of the original. It is in my primality tester that I seem to be running into trouble; no matter how many candidates I test, it never comes up with a possible prime. The tester is based on the Miller-Rabin algorithm as given on Wikipedia, with some changes based on the Python implementation on Rosetta Code.

My current code is as follows:

rsamath.c

/*
* rsamath.c
*
* Created on: 24 May 2012
* Author: tugce
* modified by J. Osako 12 June 2012
*/
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "rsamath.h"

/* generate a 64-bit unsigned random number */
uint64_t rand_u64()
{
    return ((uint64_t) rand() + (((uint64_t) rand()) << 32));
}


/* Miller-Rabin probabalistic test for primeness */
bool prime(uint64_t candidate, uint64_t iterations)
{
    uint64_t i;
    uint64_t d, s, a, a_prime, x;

    if (candidate <= 3)
    {
        return true;
    }

    if (candidate % 2 == 0)
    {
        return false;
    }

    /* determine usable values for s and d */
    s = 0;
    d = candidate - 1;

    while (d % 2 != 1)
    {
        s += 1;
        d /= 2;
    }

    if ((squareMul(2, s, UINT64_MAX) * d) != (candidate - 1))
    {
        return false; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you tell us what the errors you are getting are, as well as which compiler and platform you are using?

One thing I will recommend right off the bat is to remove the using namespace std; from both the header and the implementation file for your class, and explicitly scope the stream objects. As is explained here, this can cause a problem when using a friend function, in that the type declarations (which appear to refer to the std:: namespace) are actually referring to the global namespace - where no such type declarations exist.

std::ostream& FeetInches::operator<<(std::ostream& strm, const FeetInches right&)
{
    strm << right.feet << " feet, " << right.inches << " inches";
    return strm;
}

Second, I would stringly recommend against explicitly polling the user for the input the way you have it now. The reason for this is because you don't know for certain which I/O stream you'll be getting the input from; if you apply the operator to a file stream, for example, it may cause the input to fail.

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

As Deceptikon says, the languages themselves are not software at all. Presumably, what you want to know about are the translators - compilers and interpreters - which implement the languages.

The answer is, 'yes'. Whether they are system software or application software is entirely a matter of point of view. To try and place them in fixed categories is a pretty much meaningless act.

As for what languages the translators are written in, well, as WaltP points out, you can use any Turing-complete language to write a language translator in. This is not just an academic point, either: there were at times a number of compilers written in Fortran, back when it was the dominant language for all non-business software, and I recall one case where (due to the circumstances where the programmer was operating under) someone wrote an assembler for the 8080A in COBOL. For years most compilers were written in assembly language, at least until C became popular. I myself have written a compiler in Python, though only a toy one for a course I was taking.

In actual practice, the most widely used languages for this purpose right now is probably C or C++, though Java is not uncommon, especially in the classroom. Many translators use some sort of of special-purpose languages for creating the lexical analyzer (e.g., flex) and the parser (e.g., YACC, Bison, ANTLR), though that is hardly necessary - most commercial-grade compilers have hand-written lexers and parsers for performance reasons.

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

Well, first off, it isn't really the case that composition is superior to inheritance, so much as that they are useful for different things, and that inheritance lends itself to misuse more than composition does. The real knock against inheritance is about 'spaghetti inheritance', which is where you are inheriting from multiple base classes which aren't conceptually super-classes of the class, just to get some functionality that the base class possesses. It's a common design anti-pattern, one which has given inheritance a bad name. That, plus the fact that composition is more generally applicable than inheritance, is the real reason they drill into students to use composition rather than inheritance.

The general rule is that you should only inherit from those parent classes which the subclass clearly is a special case of. One common test for the validity of inheritance is the Liskov Substitution Principle, which (informally) states that for a given parent class, it should be possible to substitute an object of any subclass and have the object respond usefully to all possible messages which could be passed to a parent class object.

As for polymorphism, it is actually used quite widely, but again, it lends itself to misuse. Polymorphism is primarily applicable when you have a subclass which adds to the behavior of a parent class, rather than one which replaces the existing behavior entirely. For example, the BufferedReader class inherits the Reader class, but adds the buffering behavior to …

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

Which DBMS are you using? Most modern database engines have some sort of support for autoincrementing integers, which would make a lot more sense for most purposes than a text field as a primary key.

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

You can do this without a loop by computing the offset directly:

cout<<setw(5 * first_day)<<right<<i;

Note that days is not the right value for this, as it is the total number of days in the month; what you want is the number of the offset for the first day in the week (e.g., Sunday = 0, Monday = 1, Tuesday =2, etc.). You may find it helpful to have an enumeration type for this purpose:

enum DAYS_OF_WEEK {SUN, MON, TUE, WED, THU, FRI, SAT};

As for the endl, what you want to do is add a test inside the printing loop that checks to see if the current day plus the day of the week of the first day is divisible by seven. For this purpose you'll want to use the modulo operator (%), and when it is zero, then you want to start a new line.

 // first, print the first day of the week
 cout << setw(5 * first_day) << right << '1';

for (int i = 2; i < days; i++)
{
    cout << setw(5) << right << i;

    if (((first_day + i) % 7) == 0)
    {
        cout << endl;
    }
}

HTH.

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

First off, you want to change how you are setting the first day of the month. Right now, you have a fixed offset for the first day, and are then using that same offset for each successive day of the month, causing them to be printed at intervals of 36 characters each. Needless to say, this isn't what you want.

Let start by coming up with a way of computing the offset for the first day, then work out the loop such that it adds an endl after the Saturday of each week.

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

FAQ: Clearing the console The linked article goes over most of the common (and a few less common) approaches to clearing the console screen, and explains the strengths and (mostly) the weaknesses of each. It specifically explains why there is no general, portable solution to the problem (without using a third party library such as Curses), and why most of the common solutions to the issue are not reccomended. It includes a link to another article on the whys and wherefores of console programming, and another that explains the general problems involved in using the system() function.

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

Oh, and as for an alternative regarding clearing the console screen, this article covers the subject in great detail, including th reasons why system("cls") is a Bad Idea. It includes a Windows API based function for this purpose, and I tested it with my version of your program and had no trouble with it.

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

I made a few modifications to the program for you; while most of them are minor (and somewhat pedantic) corrections, the main thing I did was to separate out the encoding function from the function code(). The reason I did this was separate view from functionality: by having the actual encoding operation distinct from the user interface, it makes it easier to change either of them without changing the other. This would make a big difference if you were to decide to change to a Windows-style interface instead of a console interface.

I also made all of the strings explicitly C++ string objects rather than C-strings. This means that you aren't relying on the older C libraries as much, and specifically, that you can drop the #include <cstdio> header. I furthermore moved the references to system("cls") into a separate function, clearscreen(), so as to mitigate the system-dependence somewhat (that is to say, if you go to a different type of system, you now only need to change it in one place, rather than all over the code).

If any part of this is unclear, let me know and I'll do my best to explain it.

For the future, I recommend turning on all warnings and error messages, so that you get as much information back from the compiler as possible. If you are using Code::Blocks for your IDE (a good choice IMAO), you can go into the Compiler and Debugger under the Settings menu, and look in the Compiler Settings

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

There are a number of mistakes in this code, starting with the use of void main() rather than int main(). While the older C standard allows for it, it is a non-portable variant, and the IIRC newest version of the standard closes that loophole by requiring main() to return an int.

The next major issue is that while you declare a char pointer, you do not actually set aside any memory to store the string in. You will want to either use a static buffer:

char a[1024];

or else allocate the memory you are using dynamically:

char* a;
a = calloc(1024, sizeof(char));

If you do the latter, remember to free() the memory when finished.

Finally, in the line scanf("%s",&a);, you are taking a reference a, which is a pointer; thus, you are passing scanf() the address of a itself, not the address of the buffer you are trying to put the string into. You would want to use

scanf("%s", a);

There's still an issue with that, however, in that you aren't taking any precautions agains overrunning the buffer. This can be fixed using a string width modifier:

scanf(%1023s", a);

(There are tricks for setting the width dynamically, but that's getting a bit complicated at this stage). However, for string input, you might be better off using fgets() anyway, as it will read a string up to a maximum size, without stopping at whitespace.

#include <stdio.h>

#define BUFFER_SIZE 1024

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

First off, they are completely unrelated languages; Java was developed out of a language called Oak by Sun Microsystems, while JavaScript was created by Netscape Communications. while they share some common syntax, most of that commonality was inherited independently from C++. 'JavaScript' isn't even the original name of the language (it was initially named 'LiveScript' by its developers at Netscape), and even now its formal name is actually ECMAscript. Strictly speaking, the name 'JavaScript' refers to the Mozilla Foundation's implementation of the ECMA standard, though nearly everyone just calls it JavaScript regardless of the platform.

The languages are technically quite different as well. Java is a fully object-oriented language (sort of), uses a class system for inheritance, and is usually implemented using a bytecode compiler. JavaScript is usually (indeed, always AFAIK) a directly interpreted language, and is primarily used in a procedural style but with functional and object-oriented facilities (by way of closures), and inheritance is through prototypes (there is a newer version that has a class structure, but that never got widely accepted). The language support facilities are radically different, with the Java library being rich and sprawling, but without any overall top-down design principles, while the JavaScript library is much more constrained, and based on the Document Object Model developed for browser-oriented development.

This brings us to the last major difference: Java is by and large a standalone language, with facilities for running 'applets' inside of browsers but not being tied to browsers specifically; whereas JavaScript is (almost) …

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

Calling main() explicitly is an extremely poor idea; in fact, it is actually forbidden in the C++ standard, and the compiler ought to be giving you an error message on that (not that all compilers do). The main() function is special in a number of ways - it performs a number of initializations steps which are hidden from the programmer, for example, gathering the command-line arguments - which should not be repeated by the program after the actual code begins.

As for clearing the screen, is it really necessary? It is, as said earlier, a system-dependent operation. Now, since you're already looking at a Windows-specific program (interacting with the clipboard, etc.), it wouldn't be particularly harmful to use a clear screen, but at the same time, it is not, strictly speaking, a requirement of the program, and using it is more chrome than functionality.

In any case, the system("cls") call isn't really the best way to go about this; calling out to the shell is a rather slow process, and if you're going to be system-dependent, you may as well use the system calls themselves - though putting them in a wrapper may make sense, to preserve some amount of portability. This MS knowledge base article gives an example of how to do it programmatically; the function thy give is fairly involved, as there is no existing API function for this purpose, but it should be more or less drop-in code (though you'll need to #include "windows.h" to …

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

I've done some experimenting with your code, and modified it somewhat for testing, but I found serious issues with it. The test code I came up with is as follows:

rsamath.h

/* rsamath.h */

#ifndef RSAMATH_H
#define RSAMATH_H

int gcd(int a,int b);
int findD(int e,int n);
int squareMul(int a,int b,int n);
int totient(int m);

#endif

rsamath.c

/*
 * rsamath.c
 *
 *  Created on: 24 May 2012
 *      Author: tugce
 */

#include "rsamath.h"

/*Here is gcd function */
int gcd(int a,int b)
{
    while(a!=b){
        if(a>b)
            a-=b;
        else
            b-=a;
    }
    return a;
}

/*This is called  Extended Euclid’s Algorithm to find d. */
int findD(int e,int n)
{
    int f=e;
    int d=n;
    int x1, x2, x3, y1, y2, y3;
    int q = 0, i = 1;
    int t1 = 0, t2 = 0, t3 = 0;

    x1 = 1; x2 = 0; x3 = f;
    y1 = 0; y2 = 1; y3 = d;

    do
    {
        if (i == 1)
        {
            q = x3 / y3;
            t1 = x1 - (q * y1);
            t2 = x2 - (q * y2);
            t3 = x3 - (q * y3);
        }
        else
        {
            x1 = y1; x2 = y2; x3 = y3;
            y1 = t1; y2 = t2; y3 = t3;
            q = x3 / y3;
            t1 = x1 - (q * y1);
            t2 = x2 - (q * y2);
            t3 = x3 - (q * y3);
        }
        i++;
        if (y3 == 0)
        {
            break;
        }
    } while (y3 != 1);
    if(y2<=0) …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'd like to give you two more pieces of advice: first, separate the encryption and decryption code from the sound card code, and the sound card code from the main() function, and compile them separately, linking them together only once you tested the two library sections.

Second, you really want to trim your #includes; you have multiple entries for a number of libraries, and some libraries are included which you don't seem to need at all. Breaking the code up will help with this, as (to give one example) the main() function wouldn't need to include <math.h>, while the cipher code wouldn't need the Linux-specific <fctrl.h> and <linux/soundcard.h> headers.

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

Ah, now this is a different question. In C/C++, any given program must have exactly one main() function, but a program may span as many files as you like, and not all source files must have a main() - indeed, most source files won't, for the majority of non-trivial projects.

Can you give us a bit more information about what you're trying to do, perchance?

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

Yeah, that's what I expected, unfortunately. As I said, you need to be able to change the code page first, before you can be sure it will display the given glyphs. If you add the line SeConsoleOutputCP(65001); to the top of the program, it should do this for you.

#include <iostream>
using namespace std;

int main ()
{
    UINT old_cp = GetConsoleOutputCP();
    SetConsoleOutputCP(65001);

    wchar_t a, b, c;
    wcout << L'š';
    wcin >> a;
    wcout << L'Č';
    wcin >> b;
    c = a + b;
    wcout << L'Ć' << c << endl;
    SetConsoleOutputCP(old_cp);
    return 0;
}

However, I've done some further checking, and it seems that even if you're able to do that, it might not work with the 'standard' wide streams; apparently, they aren't properly implemented in GCC, at least, and I don't know if they are in Visual C++ either. You may need to use some Windows specific functions for this purpose, instead:

#include "windows.h"

int main()
{
    HANDLE stdout = GetStdHandle(STD_OUTPUT_HANDLE);
    if(INVALID_HANDLE_VALUE == stdout) return 1;


    UINT codepage = (UINT) 65001;
    SetConsoleOutputCP(codepage);


    wchar_t *unicode = L"šČĆ";

    int lenW = wcslen(unicode);
    int lenA = WideCharToMultiByte(codepage, 0, unicode, lenW, 0, 0, NULL, NULL);
    char *ansi = new char[lenA + 1];

    WideCharToMultiByte(codepage, 0, unicode, lenW, ansi, lenA, NULL, NULL);
    WriteFile(stdout, ansi, lenA, NULL, NULL);

    delete[] ansi;

    return 0;
}

This is a bit of a hack, but it should display the characters in question.

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

The main thing I am seeing here is that you are trying to save the characters to int variables, rather than char. While it is true that the standard char type is only 8 bits wide, and thus would not be able to hold the multi-byte characters, using an int means that the character's bytes get interpreted as their numeric value, rather than as a glyph.

The solution is to use the wide character type, wchar_t. This allows you to use a multi-byte character, with the specific size and encoding defined as compiler and system dependent. Along with this, you should use the wide-character versions of the input and output streams (std::wcin and std::wcout) rather than the standard character streams (std::cin and std::cout). This ensures that the wide characters are in fact interpreted as wide by the stream. You also need to use the capital L before any character or string literals, to indicate that they are wide literals. Thus, your code should look like this:

#include <iostream>
using namespace std;

int main ()
{
    wchar_t a, b, c;
    wcout << L"š";
    wcin >> a;
    wcout << L"Č";
    wcin >> b;
    c = a + b;
    wcout << L"Ć" << c << endl;
    return 0;
}

However, even this does not ensure that the characters will display correctly! Recall what I said about character encoding being defined as system dependent by the language standard? Well, the system first of all has to be able to display …

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

First off, you might want to use calloc() rather than malloc() for allocating arrays:

ascii=(int *)calloc(24000, sizeof(int));

It's a minor point, as there is no real difference in it result-wise, but it does make it clearer what your intent is.

Also, you are allocating memory and having enc and dec point to it, but then you assign the values of the encryption and decryption functions to those same pointers; the allocated memory is being lost, and the pointers reassigned to the new buffers allocated by the functions. This doesn't really impact the program (aside from creating a massive memory leak), but it should still be fixed.

Third, in the line

for(k=0;k<sizeof(dec);k++)

the sizeof operator is acting on an int pointer (dec), not the memory which the pointer refers to. Thus, the result of sizeof(dec) is the size of the pointer (probably either 4 or 8 bytes, depending on whether you are using a 32-bit or 64-bit Linux), not that of the buffer it points to.

Getting to the meat of the problem, we find all three of these points to be relevant to the encyrpt() function:

int *encyrpt(int text[],int e,int n)
{
    int t=0;
    int *s=(int *)malloc(24000);
    for(t=0;t<sizeof(text);t++)
    {
        int gec=(int)text[t];
        //Here computes E(M)=M^e mod n;
        s[t]=squareMul(gec,e,n);
    }
    return s;
}

Here, the allocation size appears to be wrong; you are allocating 24000 bytes, but passing this to an int*. The result is that you get 6000 integer values (assuming a 32-bit …

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

The endl manipulator has the effect of forcing a newline. If you remove it from the output line, and put it after the end of the loop, it should give the desired result:

for(int i=0; i <= 10; i++)
{
    cout << i;
    if (i < 10)
    {
        cout << " ";
    }
}
cout << endl;

Note that I added a test on the value of i so that it doesn't include the space after the last number; this might not be particularly important here, but it could come up under other circumstances where you wouldn't want a trailing space at the end of the line..

Any questions?

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

Cross-posted to DevShed
Also Warrior Forums

I posted some comments on the DevShed thread which I hope you'll find useful; I would repost them here, but it would just be a waste of the disk space for Daniweb to duplicate it. Suffice it to say, you need to give us more information before we can help you, starting with whatever code you've already written.

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

Best is awfully subjective, but I can make a few suggestions.

To start with, the main Python site actually has some excellent tutorials, as well as all of the documentation references for the language.

The Dive Into Python online text is a good one if you are already familiar with at least one other language, but it isn't really for beginners. The same can be said for the well-regarded Thinking in Python - good if you already are an experienced programmer, not so good for a rank novice. However, Eckel does mention a website called A Bite of Python as a good starting place; I haven't looked at it enough to give a recommendation, but from what I've seen it seems pretty good. I would recommend the 3.0 branch rather than the 2.6 branch, as you're better off learning the new version of the language from the start.

Think Python is a free text on the subject, an update of the venerable How to Think Like A Computer Scientist series.If it is anything like it's predecessor, it is probably a good choice for someone with no programming background at all.

I'm sure there are many others around, if you look.

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

I probably shouldn't do this, but I feel you could benefit from having some guidance in how to write this program effectively. Therefore, I'll provide you with a pair of functions which should help you in finishing the coding:

int getScores(int* student_ids, int* scores, int max_students)
{
    int id, score, head_count;
    bool duplicate = false;

    for (head_count = 0; head_count < max_students; head_count++)
    {
        do
        {
            duplicate = false;
            cout << "Enter a Student ID number (or zero to finish): ";
            cin >> id;
            cin.ignore();

            if (isDuplicate(student_ids, head_count, id))
            {
                duplicate = true;
                cout << "You cannot have duplicate Student IDs" << endl;
            }
        } while (duplicate);


        if (!id)    // student ID == 0
        {
            break;
        }

        do
        {
           cout << "Enter the Student's raw score (max. of 10): ";
           cin >> score;
           cin.ignore();
           if (score > 10)
           {
               cout << "You cannot have a score higher than 10." << endl;
           }
        } while (score > 10);


        student_ids[head_count] = id;
        scores[head_count] = score;
    }

    return head_count;
}

bool isDuplicate(int* student_ids, int head_count, int id)
{
    for (int i = 0; i < head_count; i++)
    {
        if (student_ids[i] == id)
        {
            return true;
        }
    }
    return false;
}

I deliberately covered the part you actually had working, but re-wrote it somewhat to make it a better design. Note the use of pointers instead of fixed arrays for the integer arrays.

I hope this helps you see how to write the code better. I do not guarantee that this works, …

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

The answer would depend on what you needed it for. The first question to really ask is, do you really need it in the first place? As Deceptikon said, most of the time, it is used - or rather abused - for a purpose that could be easily avoided.

In your case, the reason you want to capture a single character entry is to ensure that you get a single letter value, and ignore any other input, correct? Well, unfortunately, there isn't any portable way to do this, as different operating systems handle the console differently. Again, as Deceptikon points out, that is a case where using the <conio.h> library is a reasonable option, especially since the major alternatives - using the Win32 Console API directly, or re-writing the program as a GUI application - would require considerably more effort. You might consider doing either of those later, as you would surely learn quite a bit about Windows programming while doing so and frankly either are preferably to futzing about with something as obsolete as conio, but for the time being what you have isn't too unreasonable.

I would recommend breaking the user interface out from the game proper, however, as it would make it a lot easier to fix problems later, and would give you the flexibility to go from a console program to a GUI program with relative ease. You generally want to separate what is called the view or presentation part of the program from …

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

Pull the other leg, now; it's got bells on it.

Seriously, there's little reason to try and hide the fact that this is a homework assignment; the description and requirements are pretty much a giveaway. We don't have a problem with students coming here to get help, quite the contrary. The problem is when someone drops their assignment and demands that we do the work for them, without showing any effort on their own part. While you certainly did that with your first post, you were able to get things going an showed your work right away without whining or dissembling, which counts for something at least. But this business of pretending that it isn't a class assignment when everyone here can see that it is, makes you look a bit skeevy to the regulars here. It doesn't get you anything but distrust and a mild contempt, something you don't want to earn if you intend to ask more questions here in the future.

j509 commented: good one :) +0
WaltP commented: disembling? skeevy? I thought this was an English board! ;o) +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's get started by getting the code properly indented, so that it is readable. A quick pass through the AStyle tool highlights one of the primary problems you've got right away:

const int ITEMS = 10;
const int QUIT = 999;
int retailItem[ITEMS];
int salesTax, a;
double subTotal = 0;
double total;
salesTax = .08;

class RetailItem
{
private:
    string description;
    int itemNum;
    double price;
public:
    int getItem();
    string getDescription();
    double getPrice();
    RetailItem(string,int,double);
    void setItem(int);
    void setdescription(string);
    void setPrice(double);
};

RetailItem::RetailItem(string des,int item,double p)
{
    description = des;
    itemNum = item;
    price = p;
}
int RetailItem::getItem()
{
    return this->itemNum;
}
double RetailItem::getPrice()
{
    return this->price;
}
string RetailItem::getDescription()
{
    return this->description ;
}
void RetailItem::setItem(int item)
{
    this->itemNum = item;
}
void RetailItem::setdescription(string desc)
{
    this->description = desc;
}
void RetailItem::setPrice(double p)
{
    this->price = p;
}

int main()
{
    RetailItem obj1("Ecko Jacket",1,59.95);
    RetailItem obj2("Polo Jeans",2,34.95);
    RetailItem obj3("T-Shirt",3,24.95);
    RetailItem obj4("Snicker shoes",4,50.25);
    cout<<"#1     "<<obj1.getDescription()<<"       "<<obj1.getItem()<<"     $"<<obj1.getPrice()<<endl;
    cout<<"#2     "<<obj2.getDescription()<<"        "<<obj2.getItem()<<"     $"<<obj2.getPrice()<<endl;
    cout<<"#3     "<<obj3.getDescription()<<"           "<<obj3.getItem()<<"     $"<<obj3.getPrice()<<endl;
    cout<<"#4     "<<obj4.getDescription()<<"     "<<obj4.getItem()<<"     $"<<obj4.getPrice()<<endl;
    cout << "Enter first item number you would like to purchase or " << QUIT << " to quit ";
    cin >>retailItem[salesTax];
    while(salesTax < ITEMS &&  retailItem[salesTax] != QUIT)
    {
        subTotal += retailItem[salesTax];
        ++salesTax;
        if(salesTax < ITEMS)
        {
            cout << "Enter next item number for purchase or " << QUIT << " to quit ";
            cin >>retailItem[salesTax];
        }
        cout << "The entered item numbers are: ";
        for(a = 0; a < salesTax; ++a)
            cout << retailItem[a] << " "; …
j509 commented: thanks that helps. +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Thank you for pointing both of those issues out. I should have been more careful in this, but I was a bit rushed. My apologies if I misled anyone.

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

OK, sounds like a good project to work on. What have you done with it so far?

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

Just a quick correction: line 6 should read

if (argc == 1)

and line 13 should read

for (int i = 1; i < argc; i++)

HTH.

deceptikon commented: I was withholding rep because of line 13, but now you deserve it. :) +8