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

That depends, I would say, on how you mean to use the two methods. Personally, I would probably have only one form of the method, one which takes an istream& as it's argument; this covers both the case of a file input (ifstream&) and string input (istringstream&), and gives you additional options besides (e.g., reading from std::cin for a filter).

I would add that you may want to have it return a vector of an abstract Token class, rather than of plain std::strings. This would allow you to specialize the set of tokens a given Lexical object returns with additional information aside from the contents of the string itself.

Or perhaps you could combine the two sets of ideas, and have it return a stream of Tokens? You'd need to define a tokenstream class, as an extended form of an ios, and then... hmmn, let me think this out a bit.

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

With a bit of extra work, I think you'll find this solves (most) of the issues with your code:

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

int precedence(char c)
{
    switch(c)
    {
    case '*':
    case '/':
        return(2);
    case '+':
    case '-':
        return(0);
    }
}

void to_postfix(char *infix, char* postfix)
{
    char stack[30];
    int i=0,j=0,top=-1;
    while(infix[i] != '\0')
    {
        if(isalpha(infix[i]) || isdigit(infix[i]))
        {
            postfix[j++] = infix[i++];
        }
        else if(infix[i] == '(')
        {
            stack[++top] = infix[i++];
        }
        else if(infix[i] == ')')
        {
            while(stack[top] != '(')
            {
                postfix[j++] = stack[top--];
            }
            top--;
            i++;
        }
        else
        {
            while(top != -1 && stack[top] != '(' && precedence(infix[i]) < precedence(stack[top]))
            {
                postfix[j++] = stack[top--];
            }
            stack[++top] = infix[i++];
        }
    }
    while(top>-1)
    {
        postfix[j++] = stack[top--];
    }
    postfix[j] = '\0';
}

int main()
{
    char infix[30], postfix[30];
    fgets(infix, 30, stdin);
    to_postfix(infix, postfix);
    puts(postfix);

    return 0;
}

HTH.

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

First off, stop using the SMS abbreviations; no one will take you seriously here if you insist on that sort of thing. Write out clear, complete English sentences, to the best of your ability, please.

Second, while I know it is a picayune point to make, void main() is not valid in a portable C program; the older standard allowed it, but the only really correct form is int main().

On a related note, drop the #include <conio.h> directive - <conio.h> is not a standard header, and you don't use any functions from it in any case.

Finally, never, ever use gets() - it is too dangerous, because it is unbounded and can overrun the buffer you are reading the data into. Please use fgets() in the future.

That having been said: what is the program actually doing, and how is it failing? As it is right now, my C compiler gives three warnings when I compiler the code:

Compiling: C:\Users\Jay\Documents\Programming\postfix.c
C:\Users\Jay\Documents\Programming\postfix.c: In function 'to_postfix':
C:\Users\Jay\Documents\Programming\postfix.c:22:19: warning: comparison between pointer and integer [enabled by default]
C:\Users\Jay\Documents\Programming\postfix.c:54:15: warning: assignment makes integer from pointer without a cast [enabled by default]
C:\Users\Jay\Documents\Programming\postfix.c:55:5: warning: function returns address of local variable [enabled by default]
Linking console executable: C:\Users\Jay\Documents\Programming\postfix.exe
Process terminated with status 0 (0 minutes, 0 seconds)
0 errors, 3 warnings

The last one I suspect is the critical one - you are passing the back the value of postfix, but postfix is a local variable of to_postfix(), which means it won't have …

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

Actually, let's start over with new variable names, just to make it clearer, and add some test prints to show what is happening at each stage. I did this and was able to get the program working, in fact:

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

int main()
{
    int iterations, initial_tax_years, increased_tax_years, product_tax, total_years;
    int i, j, k;
    long int* total_tax;
    long int *annual_tax;

    printf("How many iterations to test: ");
    scanf("%d",&iterations);
    total_tax = (long int) calloc(iterations, sizeof(long int));

    for(i = 0; i < iterations; i++)
    {
        printf("How many years for the first tax increase period: ");
        scanf("%d",&initial_tax_years);
        printf("How many years for the second tax increase period: ");
        scanf("%d",&increased_tax_years);
        printf("How many years for the final tax increase period: ");
        scanf("%d",&product_tax);
        printf("How many total years to review: ");
        scanf("%d",&total_years);
        annual_tax = (long int*)calloc(total_years, sizeof(long int));
        printf("How much was the initial tax payment: ");
        scanf("%ld", &annual_tax[0]);

        /* print out the initial state */
        printf("\n\nyear 0 == %d\n", annual_tax[0]);

        for(j = 1; j <= initial_tax_years; j++)
        {
            annual_tax[j] = annual_tax[j - 1] + 1;
            printf("year %d == %d\n", j, annual_tax[j]);
        }
            annual_tax[j] = annual_tax[j - 1] + 1;

        for(j = initial_tax_years + 1; j <= (initial_tax_years + increased_tax_years); j++)
        {
            annual_tax[j] = annual_tax[j - 1] * 2;
            printf("year %d == %d\n", j, annual_tax[j]);
        }

        for(j = (initial_tax_years + increased_tax_years + 1); j < total_years; j++)
        {
            annual_tax[j] = 1;

            for(k = 1; k <= product_tax; k++)
            {
                annual_tax[j] = annual_tax[j] * (annual_tax[j - k]);
            }

            printf("year %d == %d\n", j, annual_tax[j]);
        }

        total_tax[i] = annual_tax[total_years - 1] …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think I see the problem here; you are making an understandable but incorrect assumption about how arrays work in C. In C, arrays do not start with the element one, but rather with element zero. Conversely, the last element of an array is not the size of the array, but the size of the array minus one. To put it another way, the elements of an array declared int a[4]; would be a[0], a[1], a[2], and a[3]. There is no a[4] in a four-element array in C; the 4 in the declaration is the size of the array, not the index of the last element.

Thus, the correct way to walk through an array is

int i;
int a[10];
for(i = 0; i < 10; i++)
{
    // do something here
}

There are good, if somewhat obscure, technical and mathematical reasons for zero-indexed arrays; this blog article covers one line of reasoning on the subject, and the Wikipedia article on Zero-Based Numbering gives an overview of a few more. Suffice it to say that, except for a few older languages, almost all programming languages use zero-indexed arrays, for better or for worse.

As for the compiler, you might find Visual C++ Express easier to use than CFree, I'm not sure. However, since CFree will work with the newest version of MinGW, the easier solution is to download and install MinGW, then set CFree to use the newer version …

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

OK, I just looked into CFree a bit, and found out that the default compiler for CFree Standard 4.0 is GCC for MinGW, version 2.95, a version which dates from around 2002 if I am not mistaken. That's a whole lot better than what I was worried about (ten years newer and after the C99 and C++98 standards), but still quite old.

Since CFree is a general-purpose C/C++ Integrated Development Environment that is not specific to any given compiler, you should be able to install and use a newer version of the MinGW port of GCC without any trouble, which would get you (almost) up to date with the latest version of GCC.

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

Not little changes, no; enormous ones. The entire C++ language was overhauled in the 1998 ISO standard, and again last year in the 2011 ISO revised standard. The big change in the 1998 version was the introduction of namespaces, which was what prompted the changes in the standard headers (the old headers were, for a while, allowed for the sake of backwards compatibility in older code that didn't use the namespace system, but have been phased out since then).

This is just in the standard C++ language itself. Visual C++ has a whole raftload of proprietary additions to C++, as well, and if your professor teaches those, well, they are worh knowing about, but you ought to understand that they aren't really part of the language as it is used by the rest of the world.

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

To address the last question first, it depends on which compiler you're using, and wether it is configured to catch all of these given issues. I have my compiler set to warn me about a lot of things which aren't, strictly speaking, errors in C, but which are nonetheless causes of bugs. Even with that, however, it didn't catch the problem with not having n initialized; I noticed it myself, when going through the code. As for the header issue, what it actually warned me of was that calloc() was not declared before use, and that the return value did not match the default; it took a bit of experience and familiarity with the standard library to recognize the cause of the problem.

Speaking of compiler differences: when I compile and run the code as given, I get a segfault. I tracked this down to the last of the for() loops, where you have the conditionals in the form

    for(l = (s1+s2); l<=n; l++)
    {
        ptr[l]=1;
        for(m=1; m < k; m++)
            ptr[l]=ptr[l]*(ptr[l-m]);
    }

The problem is that l (a very bad variable name, BTW - it can too easily be confused with 1 when reading the code) is being tested as less than or equal to n, which means that on the last loop, l equals n. This is a problem, because the indices of the array only go from 0 to n - 1. Thus, you are walking off the end of the array during the …

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

First off, while it isn't relevant to your particular issue, I would recommend against using void main(). According to the C++ standard, the only valid return type for main() is int, and while some compilers do accept other return types, it is strictly non-portable.

Speaking of non-portable, the <conio.h> library is specific to older MS-DOS compilers, and while some newer compilers have versions of it, they are not by any means consistent with each other. In any case, there's no real need to clear the screen, unless you were specifically instructed to by your instructor. If you eliminate the conio.h> header and the clrscr() function, you'd have portable code.

Sort of, that is... except for one more minor issue. The newer C++ standard (as of 1998, that is) changed the headers, so that <iostream.h> should now be just <iostream>. It also added a system of namespaces, which means you'll need a scope qualifier. The easiest way to have that is to add the line

using namespace std;

just after the header includes. A better way would be to explicitly scope each reference to a class or object in the std namespace, like so:

void bande()
{
    std::cout<< "Enter Base number:";
    std::cin>>b;
    std::cout<< "Enter Exponent:";
    std::cin>>e;
}

While it is more work, it gives you better control over the namespaces.

Which compiler are you using, BTW? If you are using the Turbo C++ compiler, I would strongly recommend getting rid of it; it is more than 20 …

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

In that case, could you post the exact error message as it appears in the compiler window, including the line numbers? If you could let us know which compiler and IDE you are using, it may help as well.

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

Having taken the time to compile the code and run it, I've found that the error in question occurs on line
104 (and repeated on line 142), where you have an invalid cin.operator>>() reference:

cin>>Fname>>" " >>Lname;

You cannot have any literals inside a cin>> operation. In this case, the space is unnecessary, anyway, as cin >> automagically breaks the input at whitespace. Thus, this is all you should need:

std::cin >> Fname >> LName;

Note that used the fully qualified version of the std::cin object; I recommend doing this most of the time, rather than using the using namespace std; directive. A fully working version of your code using explicit scoping would be:

#include <string>
#include <iostream>
#include "lab_14_head.h"


void showMenu()
{
    std::cout<<std::endl;
    std::cout<<"********User Menu***************************************************"<<std::endl;
    std::cout<<"Enter 1 to play with a void function without parameters "<<std::endl;
    std::cout<<"Enter 2 to play with a void function parameters "<<std::endl;
    std::cout<<"Enter 3 to play with a value-returning function without parameters "<<std::endl;
    std::cout<<"Enter 4 to play with a value-returning function with parameters "<<std::endl;
    std::cout<<"********User Fullname***********************************************"<<std::endl;
    std::cout<<"Enter 5 to play with a void function without parameters "<<std::endl;
    std::cout<<"Enter 6 to play with a void function parameters "<<std::endl;
    std::cout<<"Enter 7 to play with a value-returning function without parameters "<<std::endl;
    std::cout<<"Enter 8 to play with a value-returning function with parameters "<<std::endl;
    return; //no value is returned here
}
//this is a void function without parameters
//it gets two numbers from the user and prints the sum
void fun_1( )
{
    //local …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, first things first: I know that you were probably instructed to put the functions in the header file, but in fact you only want the function prototypes declared there; you'll want to put the actual functions in a third file, which would then be linked into the program at compile time.

#ifndef LAB_14_HEAD_H
#define LAB_14_HEAD_H
//This function shows the user menu

#include <string>

void showMenu();
void fun_1();
void fun_2(int x, int y);
int fun_3( );
int fun_4(int x, int y);
void fun_5();
void fun_6(std::string Fname, std::string Lname);
std::string fun_7();
std::string fun_8(std::string Fname, std::string Lname);

#endif

Just how you would do this depends on your working environment and how you are compiling it; which is to say, it works differently for Visual Studio than how it works in Code::Blocks, which is different from how you would do it from the command line, etc.

As for the reasons why you don't want the functions themselves in the header files, this posting gives a thorough, if tongue-in-cheek, explanation for it as well as some historical context.

Now, to address the specific error message in question, let me ask you, does it say what line the error is occurring on? I suspect that it is a namespace issue, but without more information I cannot say for certain.

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

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

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

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

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

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

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

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 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

On a conceptual level, I would recommend looking into the Flyweight pattern. The basic principle is to have a class which represents the common aspects of the objects (e.g., sprite sheets) as class members, then have the Flyweight objects instantiate just the details which the specific object needs (e.g., position, color map). The Wikipedia page has a decent example of how to write a Flyweight class and Flyweight Factory (which also allows you to avoid repeated memory allocations by having a pre-existing pool of Flyweight objects to draw from).

On a practical level, you would probably have some abstract parent class for all of the objects you are using (the Flyweight class), and a Factory class which would be used to produce (or retrieve) objects of the appropriate sub-class. The Flyweight class would provide an interface for the shared behaviors, as well as holding any properties shared by all members as class ( static ) variables. The Flyweight Factory class would have a method that takes some sort of marker that indicates which subclass of the Flyweight class to use, as well as any properties specific to the Flyweight object; it would check to see if any objects of that sub-class already exist, and if so, returns one of them, otherwise, it would create a new object of the desired sub-class and return that. The parent Flyweight class (and it's sub-classes) would hold the shared information as static class variables; only the specifics of the …

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

Colors are usually represented by three color gradients (either Red-Green-Blue for 'additive color' or Cyan-Yellow-Magenta for 'subtractive color'). This is because the human eye can differentiate three different clusters of wavelengths, with some overlap, so colors 'between' the main detected colors, such as orange, are actually detected by the green and red receptors, and so appear as a combination of the two.

Why am I mentioning all of this? Because you are using four sets of colors to represent the spectrum, which is unusual. What does the fourth number represent: 'pure' black (as with the 'Key' of the CMYK model? Pure white? Grayscale or 'tone'? An Alpha channel (transparency)? Or do you know at all? All this may be relevant to how you store the numbers, as is Moschops question about the range of the values (because that will tell you how many bits you'll need to represent each color).

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

What it is complaining about is the fact that you have the prototypes for the functions, but the functions themselves aren't implemented anywhere. In other words, the functions are declared, but not defined. You need to have the actual implementation somewhere, either in this file or in another one which is linked with it at compile time.

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

Assuming you are using an ifstream to read the file, then function you want is seekg() , which allows you to set the 'get pointer' in a file stream (the point at which the next read will begin). If you follow that link, it has an example of how it is used.

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

Ah, sorry, I was convinced that was the source of the issue.

Could you post the exact error message, please? There may be some detail in it that would give the cause for it.

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

Are you sure that it is line 45 of the main.cpp file? AFAICT, the problem is on line 45 of playlist.cpp, where you have the print() function incorrectly associated with class 'contact'.

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

What is happening is that, because the header file is being included in both of the compiled files, the two globals are indeed being re-declared, once in each file. You need to change the header so that both are declared as extern :

#ifndef MAIN_H
#define MAIN_H 1

extern int a;
extern int b;

#endif

Then you need to actually declare the variables in either main.cpp or secondary.cpp (but not both):

#include "Main.h"
#include <iostream>
void Engine();

int a;
int b;

int main()
{
    b = 10;
    a = 5;
    std::cout << a << b;
    Engine();
}

The declaration in main.cpp is the actual declaration; the one in the header is just to allow other files to know that they exist.

Note also the use of include guards, which are to prevent a different sort of redefinition issue.

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

What is timeFactor for, and under what circumstances is it less than or equal to zero?

Also, have you considered making this part of the AI part of the enemy objects themselves, rather than part of the overall code? (I am assuming that Enemy is a class rather than a structure).