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

First off, I would say that this is different enough that you would have been better off creating a new thread, rather than posting in one several months old. Just for future reference.

While I cannot say for certain without seeing the code, from the error message given it sounds like the issue is namespace scoping. You see, the majority of objects and classes in the standard library are in the std namespace, and have to be scoped for it in order for them to be visible, even if you have the headers which hold them #included already . To do this, you have three options:

  • You can explicitly scope each reference to the object by prepending them with the std:: scope marker; e.g., std::cout, std::endl, std::string, etc. This gives you the best control over the namespace scope, and is the preferred approach, but can be tedious to use.
  • You can add the entire std namespace to the local scope, by using the directive using namespace std; at the top of the source file, right below the #include directives. This is the easiest solution, and the most common, but it loses most of the advantages of having separate namespaces. Most professional programmers avoid this for all but the most trivial programs.
  • You can add the individual clases or objects to the local scope, by using the using X::Y form of the directive, e.g., using std::cout;. This lets you use that specific objects without explicit scoping, without polluting your local namespace …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I noticed a serious bug in the program: you are allocating ptr based on an uninitialized value for n, which means that the size of ptr could be nearly anything. You'll need to read in n first, then allocate ptr, and only after that should you read in the first element of ptr. This also means that you'll need to free() the buffer pointed to by ptr on each iteration of the outer loop.

Interestingly, I compiled and ran this (under Windows 7, MinGW GCC 4.4.1 with -Wall) and got dinged for not including <stdlib.h> (required for calloc()). Once I fixed that, I was able to get it to compile, but it would fail with a protection violation on this line:

scanf("%d",&ptr[0]);

I fixed the format string to

scanf("%ld", &ptr[0]);

and it read in correctly at that point.

Oh, and I would strongly recommend adding prompts for each input, so that it is clearer which value is getting set when. I know you know the program, but without some sort of clue, it would be easy to get lost if your entering several iterations.

    for(il=0; il<s; il++)
    {
        printf("n: ");
        scanf("%d",&n);

        ptr=(long int*)calloc(n, sizeof(long int));
        printf("t[0]: ");
        scanf("%ld", &ptr[0]);

        printf("s1: ");
        scanf("%d",&s1);

        printf("s2: ");
        scanf("%d",&s2);

        printf("k: ");
        scanf("%d",&k);

        /* and so on */
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In addition to Trentacle's questions, I would also ask, what compiler are you using, under what kind of system? The reason I ask is because, while a ten million item array is almost certainly excessive, it should be possible to declare and use one under a modern 32-bit or 64-bit compiler - I have no trouble declaring such an array under either Visual C++ 2010 Express or MinGW GCC 4.4.1 x86, for example, and I assume that Pelles C would be able to as well - but an older, 16-bit compiler almost certainly wouldn't be able to declare an array larger than 65535KiB total size.

Also, you fail to mention what it is an array of. Keep in mind that an int array would require more memory than a char array of the same size, for example.

As for alternatives, it would depend on the nature of the data being stored in the array. If it relatively sparse - that is to say, most of the values aren't being used, or are set to some default value - it may be possible to use a linked list to emulate a sparse array. If the data is in any way heirarchical, a tree or some other complex structure may be useful for it. If only part of the data is needed at any given point - which is generally the case - It may be possible to use a to keep part of the data on disk rather than …

Ancient Dragon commented: great answer :) +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am going to over-step the usual rules about how one is supposed to help people here, but only because I think you need a good example for how to work with structures and strtok(). While the meanings of the different aspects of this are purely speculation on my part, I think tha this is close to what you want:

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

#define BUFFER_SIZE 15

typedef struct Packet
{
    unsigned int id;
    unsigned int arrivalTime;
    unsigned int transmissionTime;
    unsigned int priority;
} PACKET;

struct
{
    size_t message_size;
    PACKET* packets;
} Message;

int main()
{
    FILE* file;
    size_t i;
    char packet_description[BUFFER_SIZE];
    char *token;
    char* textFile = "data_filetest.txt";

    if((file=fopen(textFile, "r"))!=NULL)
    {
        fgets(packet_description, BUFFER_SIZE, file);
        sscanf(packet_description, "%u", &Message.message_size);
    }

    Message.packets = calloc(sizeof(PACKET), Message.message_size);



    for(i = 0; i < Message.message_size; i++)
    {
        fgets(packet_description, BUFFER_SIZE, file);
        token = strtok(packet_description, ":");
        Message.packets[i].id = atoi(token);
        token = strtok(NULL, ",");
        Message.packets[i].transmissionTime = atoi(token);
        token = strtok(NULL, ",");
        Message.packets[i].arrivalTime = atoi(token);
        token = strtok(NULL, "\n");
        Message.packets[i].priority = atoi(token);
    }
    fclose(file);

    for (i = 0; i < Message.message_size; i++)
    {
        printf("Packet #%u, Priority %u: ", Message.packets[i].id, Message.packets[i].priority);
        printf("transmitted at %u, arrived at %u\n", Message.packets[i].transmissionTime, Message.packets[i].arrivalTime);
    }
    printf("total message size: %u\n", Message.message_size);

    return 0;
}

You'll need to make the appropriate changes to match the actual interpretations of the different fields.

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

On the one hand, I agree with veedoo regarding the use of a general-purpose editor; it is often better to have one editor which you are well-familiarized with, than to jump between different editors based on the language. OTOH, there are always circumstances where you won't be able to use your favorite tools, so being familiar with several may have its place as well.

If I may ask, which compiler are you using? This could influence which IDEs are suitable or available; for example, Code::Blocks can work with several different compilers with little effort, including the MinGW GCC (the default) and the Microsoft and Borland C++ compilers. Others, such as Visual C++, are essentially compiler-specific (it is possible to use it with other compilers, but it is so much work to set up that it's not worth the effort). Also many compilers come with IDEs these days, even strictly C language compilers such as Pelles C.

As for which language to learn first, well, in my arrogant opinion, both C and C++ are languages best learned as one's third or fourth language; you generally want to have a good grasp of basic programming before digging into the lower-level details which C excells at, while C++ is a bit of monster, a giant language which gives you not just the rope to hang yourself with, but the scaffold, trapdoor and lever, too. My experience is that most newcomers can learn a higher-level scripting language, then an assembly …

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

I would actually recommend using template specialization and the string::find() method instead:

template<>
bool CustomType<std::string>::Contains(const std::string& literal, bool CaseSensitive)
{
    std::string s(literal);

    if (!CaseSensitive)
    {
        for (size_t i; i < s.size(); i++)
        {
             s[i] = tolower(s[i]);
        }
    }

    return this->find(s);
} 

template<>
bool CustomType<char *>::Contains(const char* literal, bool CaseSensitive)
{
    std::string s(literal);
    std::string self(this);

    return self.Contains(s, CaseSensitive);
}

template<typename T>
bool CustomType<T>::Contains(T literal, bool CaseSensitive)
{
    throw("Not a literal type.");
}

Note that this works if you have a string for both the template type and the function argument, or a char pointer for both, but not when mixing the two. You would still need to overload the function to get that added functionality, if you want it:

template<>
bool CustomType<std::string>::Contains(const char* literal, bool CaseSensitive)
{
    std::string s(literal);

    return this->Contains(literal, CaseSensitive);
}

template<>
bool CustomType<char *>::Contains(const std::string& literal, bool CaseSensitive)
{
    std::string self(this);

    return self.Contains(literal, CaseSensitive);
}

I can't promise that this works, but AFAIK it should be more or less correct.

triumphost commented: Best Idea! I used this without the find because find can't be used on vectors. But Good! =] +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Rubberman: To be more specific, for any regular grammar, there is a Deterministic Finite Automaton (DFA) capable of accepting the language described by the grammar. Because DFA are very easy to code, and can be generated automatically, almost every modern language is designed so that the lexemes form a regular language. Thus, it is typical to define the lexical analyzer by creating a regular grammar for the lexemes, and create a DFA to implement it. The approach I demonstrated above is a less formal version of this, but it still works by implementing a DFA; if I were being more formal, I (or the preferably, the OP) would have defined a grammar for the lexemes first, then worked from the production rules step-by-step. Since this is clearly a course assignment, I wouldn't have suggested using a lexer generator, though it is good to point that out.

DFA are not capable of recognizing context-free grammars, which includes pretty much all Turing-complete programming languages (those which aren't themselves context-sensitive, that is; note, however, that the fact that the language's semantics are Turing-complete does not require the language's grammar to be recursively-enumerable). Thus, a parser for most programming languages has to be more complicated than a DFA, requiring the equivalent of a Push-Down Automaton to recognize it. This is why parsers and lexical analyzers are different from each other.

Without more information (say, a pre-defined grammar written in

Sokurenko commented: oh i see now, i can write regular expression for every automata bot not other way :) +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Rather than eliminating code, in this case you need to add a line just above the first while() statement (line 20):

head = newNode;

This sets the head of the list, which you'll need in order to access the list as it progesses.

There's a problem within the while() loop itself, as well; rather than setting newNode->link to NULL, you need to set it to a new node, then progress newNode itself.

    newNode = new nodeType;
    head = newNode;  // initialize the handle for the list
    while(!EOF)
    {
        getline(reeaad,newNode->info);
        newNode->link = new nodeType;
        newNode = newNode->link;
    }

Otherwise, you are simply overwriting the data as it comes in.

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

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

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

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

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

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

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

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

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

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

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

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
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

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

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

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

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

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

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

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

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

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

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

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

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

const BUFFER_SIZE = 1024;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

bill = totalCost(number, price);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

PlayerFeet.SetImage(iFeet);

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

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

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

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

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

Cross-posting is generally frowned upon, as it causes a duplication of effort on the parts of the two groups.

zeroliken commented: and there's the proof +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You may find my Passim assembler useful as a guide for tokenizing and symbol table manipulation. While it is in C rather than C++, it should be familiar enough to make sense out of.

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

The problem is occurring because you are using the initialization syntax for what is in fact not initialization. When you are setting the value of a variable that is declared elsewhere, you cannot use the initialization syntax for an assignment, even if you had not yet set the variable. You need to set each member of the array separately.

khanthegamer commented: the dude knows what he's talkin about +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Try changing the sprintf() like this:

sprintf(fname, "%s\\Reports\\%d.txt", directory, s.admno);

The '%s' is used to interpolate strings, while '%d' is used to interpolate decimal integers. When you use '%d' on a C-string - which is, after all, just a pointer - you get the address of the string in question.

You also need to use double backslashes ('\\') for the path, as single backslashes are treated as escape markers. To show the backslash itself, you need to escape the escape character, as it were.

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

I've done some checking, and apparently Turbo C++ did have a version of the header <dir.h> , which may include a getcwd() which you can use. At least, I think that's what this thread implies (look down to the OP's reply to the first answer for the relevant comment).

EDIT: Further checking turns up a Google book copy of Programming in C++ by D. Ravichandran. According to this book, Turbo C++ 3.0 did have a getcwd() function, as well as another named getcurdir() . These should do what you need.

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

Sorry, that was my mistake - I failed to close the two open brackets. It should go as follows:

for (int i = 0; i < 8; i++) {
                      if (a[i] == goalTotal) {
                          cout << endl << "Player Wins" << endl;
                          win = true;
                          break;
                      }
                  }
jankeifer commented: he's awesome! +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, OK, I see the issue now. On that particular line of code, you consistently mistyped parsedLine as parsedline (with the lowercase 'l') and that's what it is complaining about - as far as the compiler is concerned, parsedLine and parsedline are completely different identifiers.

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

Since you are already testing for wins, we can use that to simplify the loop exit. First we'll add a Boolean variable named win and initialize it to false:

bool win = false;

Then we'll simplify the test for winning:

for (int i = 0; i < 8; i++) {
                      if (a[i] == goalTotal) {
                          cout << endl << "Player Wins" << endl;
                          win = true;

Finally, we change the conditional of the do/while() loop:

while(!win);

Try that and see if it works.

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

OK, to start with, since you are using more or less the same data members in both versions of the qa class, let's apply some basic reusable design by combining the two related classes into one, and separating this new class from the main program files. This will allow you to ensure that the two classes don't diverge in some way that would break them both, and make it less confusing for anyone trying to read these programs later. Since you are using an IDE that has code completion, let's write out the new class name in full as QuizAnswer .

Second, I notice you are including the <string> header, but don't seem to be using the string class itself. If you're allowed to use strings for this project, then I would recommend doing so, as it would simplify the data reading and writing if you didn't have to worry about the string lengths all the time the way you do with C-strings.

quiz.h

#ifndef QUIZ_H
#define QUIZ_H 1

#include <iostream>
#include <fstream>
#include <string>


const unsigned OPTION_COUNT = 4;

class QuizAnswer
{
    std::string question;
    std::string option[OPTION_COUNT];
    int answer;

public:
    void getques()
    {
        std::getline(std::cin, question);
    }

    void getopts();

    void getans()
    {
        std::cin >> answer;
        std::cin.ignore();
    }

    void write(std::ofstream& output);
    void read(std::ifstream& input);

    void putques()
    {
        std::cout << question << std::endl;
    }

    void putopts();
    int putans();
};

#endif

quiz.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "quiz.h"


void QuizAnswer::getopts()
{
    for (unsigned i = 0; i < …
rajatchak commented: Just Awesome!! Mastermind!! +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
for(int i = 0x21; i <= 0x7E; i += 6)
        {
            cout << setw(6) << static_cast<char>(i) << " = " << setw(3) << i;
            cout << setw(6) << right << static_cast<char>(i + 1) << " = " << setw(3) << i + 1;
            cout << setw(6) << right << static_cast<char>(i + 2) << " = " << setw(3) << i + 2;
            cout << setw(6) << right << static_cast<char>(i + 3) << " = " << setw(3) << i + 3;
            if ((i + 4) < 0x7f)
            {
                cout << setw(6) << right << static_cast<char>(i + 4) << " = " << setw(3) << i + 4;
                cout << setw(6) << right << static_cast<char>(i + 5) << " = " << setw(3) << i + 5;
            }
            cout << endl;
        }
    }

But i was not able to understand this loop. Can you please explain it step by step, that will be very grateful of you. You see it differs from my loop a lot.

Is there any table you can show me regarding 0x21, 0x7E? And why in each loop i is incremented by 6? And the why those 4 cout statments. I think as long as i don't understand that Interrupt values(I am not sure, if they are called so), i may not be able to understand this loop & same goes for that if statement too.

Oops, I meant to explain about the hex values earlier, but forgot. Values beginning with '0x' are hexadecimal value, that is, …

PrimePackster commented: This explained a lot for me +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Getting back to the code itself, I would strongly recommend separating the sorting operation into it's own function, which would let you test it separately from the input and output code. This would help narrow down the location of the problem. Something like this should do:

void bsort(double arrayOne[], int size)
{
    for (int i = 0; i < size; i++)
    {
        double currentMin = arrayOne[i];
        int currentMinIndex = i;

        bool needNextPass = true;

        for (int k = 1; k < size && needNextPass; k++)
        {
            needNextPass = false;
            for (int i = 0; i < size - k; i++)
            {
                if (arrayOne[i] > arrayOne[i + 1])
                {
                    double temp = arrayOne[i];
                    arrayOne[i] = arrayOne[i + 1];
                    arrayOne[i + 1] = temp;

                    needNextPass = true;
                }
            }
        }
    }
}

NOTE: this is not tested code. I simply modified what you already had into a stand-alone function; you'll still need to debug it.

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

I just noticed two serious problems with the code I posted. Here's the corrected code (I hope):

//************************************************
    void insertAfter(int val, Node* ptr)
    {
        if (head == NULL)
        {
            head = new Node(val, NULL);
            return;
        }

        Node *current;
        //used to hold a copy of the current list.
        Node *previous;
        //used to know the value of the current element that must
        //be shifted down one.
        

        current = previous = head;
        
        while(current != NULL)
        {
            if (current == ptr)
            {
                ptr->setNext(new Node(val, ptr->getNext()));
                return;
            }
            previous = current;
            current = current->getNext();
        }

        // reached the end of the list
        previous->setNext(new Node(val, NULL));
    }
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

One thing I noticed (aside from your indentation, which needs improving) is that the project said to set the file to append mode. Thus, you should change the open() call to:

file.open("output.txt", ios::out | ios:app);

This ensures that the data is added to the end of the file, rather than overwriting the data already there.

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

Odd, I was having what is in some ways the opposite problem - when I compile and run the program, it accepts the first set of questions and answers, then prints out the series of inquiries for the remaining questions all at once, then ending.

Enter the limit of questions
4
Enter the question
why

enter the four options
why not
because
who knows
fish

Enter the answer for the respective questions
fish
Enter the question
enter the four options
Enter the answer for the respective questions
Enter the question
enter the four options
Enter the answer for the respective questions
Enter the question
enter the four options
Enter the answer for the respective questions

While I was working on that problem, I noticed one thing: as it is now, you are overwriting each question with the next one. You want to have q be a pointer to qa, and assign it a dynamically allocated array. You also need to change how you write to the file, as the way you're doing it now won't work - you need to 'serialize' the separate members of the object one at a time to get consistent results.

This code seems to work now:

#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>

using namespace std;

class qa
{
    char question[35];
    char option[4][20];
    int ans;    //correct option no (eg 0 1 2 3)

public:
    void getques()
    {
        cin.getline(question, 35);
    }


    void getopts()
    {
        for (int i = 0; i < 4; …