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

To begin with, please use [code] tags around all code samples in the future, especially ones as large as this. This is very important, as the code tags force the software to retain the indentation; without them, the code is almost impossible to read.

#include <iostream>
#include <fstream>
#include <math.h>
#include <string>
using namespace std;

float ran1(long *);

#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define NTAB 32
#define NDIV (1+(IM-1)/NTAB)
#define EPS 1.2e-7
#define RNMX (1.0-EPS)

float ran1(long *idum)
{
    int j;
    long k;
    static long iy=0;
    static long iv[NTAB];
    float temp;

    if (*idum <= 0 || !iy)
    {
        if (-(*idum) < 1) *idum=1;
        else *idum = -(*idum);
        for (j=NTAB+7; j>=0; j--)
        {
            k=(*idum)/IQ;
            *idum=IA*(*idum-k*IQ)-IR*k;
            if (*idum < 0) *idum += IM;
            if (j < NTAB) iv[j] = *idum;
        }
        iy=iv[0];
    }
    k=(*idum)/IQ;
    *idum=IA*(*idum-k*IQ)-IR*k;
    if (*idum < 0) *idum += IM;
    j=iy/NDIV;
    iy=iv[j];
    iv[j] = *idum;
    if ((temp=AM*iy) > RNMX) return RNMX;
    else return temp;
}
#undef IA
#undef IM
#undef AM
#undef IQ
#undef IR
#undef NTAB
#undef NDIV
#undef EPS
#undef RNMX

//-------------------------------------------------------------------------------------

//--------------------------------------Defining Energy Function--------------------
double annint(double, double);

double annint (double xcoz, double box) //If xcoz is not between (-0.5 to 0.5 * box) it is taken as part of another box
{
    double co1, co2;
    if (xcoz > 0)
    {
        co1 = (int(xcoz/box))*box;
        return (xcoz-co1);
    }

    else if (xcoz < 0)
    {
        co2 = (int(xcoz/box))*box;
        return (xcoz-co2);
    }
    else
        return(0);
}

// The LJ parameters for …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As an aside: I'd strongly recommend breaking this up into multiple header and implementation files, both to make it more modular, and to reduce the amount of clutter in the main program file. Here I've done this for you to show you how to do it, if you haven't done so before; I've made the necessary changes to make it possible in the process, and this compiles and runs correctly under GCC 4.4.1/Code::Blocks 10.5 .

rpg.cpp

//RPG Game
#include <iostream>
#include <windows.h>
#include <string>
#include <conio.h>
#include <vector>
#include <dos.h>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include "utility.h"
#include "Creature.h"

using namespace std;
HANDLE  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
string selection;
const int LINE_LENGTH = 75;

int main()
{
	vector<Creature> characters;
	Creature player;
	string menuType;
	int menu = 0;
	char a ='q';
	string hint;
	vector<vector<string> > menOp(2, vector<string> (2));
	int x = 0;
	int y = 0;
	int num = 0;
	string displayTextBefore = "";
	string displayTextAfter = "";
	for(bool endgame = 1; endgame != 0;)
	{
		switch(menu)
		{
		case 0:
			menuType = "	|Main Menu|";
			menOp[0][0] = "Start Game";
			menOp[0][1] = "Game Options";
			menOp[1][0] = "Select Character";
			menOp[1][1] = "Exit";
			hint = "W, A, S, D are to move and space to select";
			break;
		case 1:
			menuType = "	|Options Menu|";
			menOp[0][0] = "Controls";
			menOp[0][1] = "Color Scheme";
			menOp[1][0] = "About";
			menOp[1][1] = "Back";
			hint = "Options are cool.";
			break;
		case 2:
			menuType = "	|Character Menu|";
			menOp[0][0] = "Select Character";
			menOp[0][1] = "Create Character"; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am assuming you meant Visual C++, not Visual Basic. Otherwise, you've gotten very confused about the language you are using :?:

The error indicates that the function _tmain() is missing. Now, in UNICODE enabled Windows programs, _tmain() is the equivalent of the main() function in regular C++. That you are getting this now, but not before, seems to me to imply that you'd changed the settings in the project to compile the program for UNICODE, whether you were aware of doing so or not. At least, that's my impression fit it; others may know more about this than I do.

A search on this matter comes up with this advice:

Please change the "subsystem" in your linker settings from "Windows" to "Console".

Whether this will do the trick or not, I am not sure. An alternative solution proposed by R. Stilskin is to

Create a new project following these steps:

When you start the new project wizard, click Win32 Console Application, enter a project name, click OK, then on the next screen click "Application Settings", then "Console application" and "Empty project".

That gives you a completely empty project, so click on Project/Add New Item/C++ File, enter a filename for your main file, and that will open an empty .cpp file.

I am pretty certain that the latter should work even if the former does not.

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

To start with, you need to be more careful about capitalization. C++ is a case-sensitive language; MyList is not the same as MyLIST or myList . This alone could be the source of some of the errors.

Secondly, you don't want to rename an object to something else; you want to copy the object to another object. Talking of 'renaming' is likely to confuse everyone, since you cannot do that.

Now, the reason that the MyList i = new MyList(); doesn't work is because the new operator returns a pointer to a newly allocated object, whereas declaring the List the way you have creates a local object of type MyList - not a pointer. if you declare it as

myList * list = new myList();

you'd be on the right track.

Note, however, that you need to delete the allocated memory when you're done with it:

MyList* MyList::mult (MyList a, MyList B)
{
    int count;

    for ( int i = b.size; i>0; i-- ) //in our case b.size=3 so it should create 3 new list
    {
        MyList* list = new MyList();

        for(int j = b.size - 1; j>0; j-- )
        {
           for(int y = a.size - 1; y>0; y--) 
           {
                list[count]= a[y]*b[j]; //multiplication not every case contemplated here
                count++;//counter to fill the new array 
           }
        }
    }
    return list;
}

This still isn't complete, however, as you need to be able to allocate a MyList with a given list size, which means that the MyList()

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

The link which WaltP provided is to a page for precisely that, actually; this link here gives details on different approaches to indent style, with a specific style (Allman) highlighted. A broad search on indent style or brace style should turn up a plethora of information.

If all else fails, you might also look into editing your code with an IDE that has an auto-indent feature. I have lately been using Code::Blocks a lot lately, and that comes with the Astyle tool which I'd used earlier (under Plugins). Visual C++ Express has a good auto-styler as well.

What editor or IDE are you using? Chances are, it already has support for auto-indentation, even if you don't know it.

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

You may be able to modify it such that it inserts a space when an operator is found, but I'm not sure that it would work consistently.

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

You would do better with a stack of strings rather than chars, I think. You then could tokenize the input into strings, and push the strings onto the stack.

A better approach might be to use a discriminant union (that is, a structure with a type marker and a union holding different possible values) to represent the tokens:

enum TOKEN_TYPE {INTEGER, RPAREN, LPAREN, OPERAND};

struct Token
{
    TOKEN_TYPE type;
    union
    {
        char operand;
        int integer; 
    } value;
};

stack<Token> st;

Better still might be to make an abstract Token class, then subclass it with IntToken and OpToken classes, which then could have the appropriate variables and methods to hold and return the values appropriately.

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

You never allocate the memory for the name and branch variables, so when you copy the strings to them, they end up writing to random locations in memory. Add the following to the new and delete operators and it should fix the issue:

void *student::operator new(size_t size)
{
	void *p;
	p = malloc(size);
	(reinterpret_cast<student *>(p))->name = reinterpret_cast<char *>(malloc(16));
	(reinterpret_cast<student *>(p))->branch = reinterpret_cast<char *>(malloc(5));
	return p;
}

void student::operator delete(void *p)
{
  	free(reinterpret_cast<void *>(reinterpret_cast<student *>(p)->name));
  	free(reinterpret_cast<void *>(reinterpret_cast<student *>(p)->branch));
	free(p);
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Your description of the problem you're having wasn't very clear; you say you want to search from an input file, but right now, all you're doing is reading in data from the console. Can you explain the problem better?

If you don't mind me asking, why do you have the createNewBunny() function instead of a conventional constructor?

Also, can you please fix the code indentation? As it is, it's very inconsistent, making it hard to read the program; I had to copy it into an editor and use AStyle to be able to read it at all.

Finally, you might want to move the references to system("clear") into a function, for the reasons I explained in this thread, as well as because most of the posters here are running under Windows rather than *nix; having a function for it would make it easy to change it to system("cls") (the Windows equivalent of system("clear") ) if they want to test the code.

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

I've gone over the segfault problem, and tracked it down to where you initialize line_counter to 1; you want to initialize it to zero, instead. As it is now, it over-counts the lines by one.

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

If you put the final while() conditional at the beginning of the main() function, and put braces around the rest of the function, it should loop around the whole function:

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>

using namespace std;

#define DEBUG 0

int Password = -1;
int Option = -1;
char Complete;
string Display;

void pause()
{
 #if (DEBUG != 1)
    system("pause");
#endif
}

void clearScreen()
{
#if (DEBUG != 1)
    system("CLS");
#endif
}

void View_Account()                                                                  //View All Available Accounts
{
    clearScreen();

    cout << "--Viewing All Available Resources--\n" << endl;

    {
        ifstream File ("Log.txt", ifstream::in);

        if(File.good())
        {
            while (!File.eof())
            {
                getline (File, Display);
                cout << Display << endl;
            }
            File.close();
        }
    }
    cout << "\n\nComplete (Y/N): ";
    pause();
}

void Modify_Account()                                                                //Modify All Available Accounts
{
    cout << "Modify Account";

    pause();
}

int main()
{
    while (Option != 6)
    {

        while (Password != 1234)
        {
            clearScreen();

            cout << "Welcome to the MAC Database Search Facility\n" << endl;            //Log In Screen
            cout << "Please enter your password now: ";

            cin >> Password;                                                            //User Input
        }
        clearScreen();

        cout << "Welcome ****, please select your option\n" << endl;                    //Welcome Screen

        cout << "1 - View All Accounts" << endl;                                        //All Available Options
        cout << "2 - Modify an Account" << endl;
        cout << "3 - Delete an Account" << endl;
        cout << "4 - Add an Account" << endl;
        cout << "5 - Search Accounts" << endl;
        cout << "6 - Exit\n" << endl;

        cin >> Option;

        switch (Option)                                                                 //Switch …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops, I missed that. You need to check whether line_counter is zero in your loop conditional, otherwise it will try to read an non-existent line, causing the segfault.

while(choice != 'q' && line_counter > 0)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

i dont want the value of i ,but still i passed it by reference but no results..

I'm puzzled, then. If you don't want the value of i after the function, and you aren't using the passed value of i , why have it passed as an argument in the first place? Why not have a local variable to use as the index?

Oh, and you really need to fix your indentation. Here is your code with indentation in Allman style, with i changed to a local variable:

bool validRook(char board[][8],int a[])
{
    if(a[0]<a[2])
    {
        for(int i=a[0]; i<a[2]; i++)
        {
            if(board[i][a[1]] != ' ')
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
    else if (a[0]>=a[2])
    {
        for(int i=a[0]; i>a[2]; i--)
        {
            if(board[i][a[1]] != ' ')
            {
                return false;
            }
            else
            {
                cout << "destiny is biggerrrrrrrrrrrrrrrrrrrrrr";
                return true;
            }
        }
    }
    else
    {
        cout << "source is biggerrrrrrrrrrrrrrrrrrrrrr";
        return false;
    }
}

Which style you use isn't very important; what matters most is as consistency. Your current code indentation and brace style is very inconsistent, making it especially hard to read.

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

Aside from some extremely inconsistent formatting, I can see a number of issues with this:

  • You don't appear to be testing whether the destination (destiny?) is still in the same column as the original position. I realize that you aren't addressing horizontal movement yet, but you should at least confirm that it isn't moving horizontally.
  • The argument i is passed to the function, but then reassigned without checking it's original value; you simply use it as an index. Was this intentional, and if so, why? If you need to get the value of i after the function is ended, then you'll need to pass it as a reference.
  • On a slightly related note, I would rename a to something more descriptive, such as move . That's just me, of course.
  • The cases of a[0]<a[2] and a[0]>=a[2] are both exhaustive and mutually exclusive; thus, while the compiler won't detect it as such, the final else clause is 'dead code', that is to say, the program will never reach it.
  • You might want to consider using a structure to represent the moves, rather than just an array; something like this:
    struct Move {
        int startRow;
        int startColumn;
        int destRow;
        int destColumn;
    };

    This would generally be easier to read than a bare array.

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

I am not familiar with a pseudo-stack, myself. Stacks are common enough, yes, but not pseudo-stacks, at least not in the usual terminology. Can you tell us the context in which you've encountered this term?

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

While it is probably more than I should be giving you, since it is very nearly the complete program, I figured this would make it clearer to you. I am especially pleased to have found out how to print the box drawing characters correctly, as well.

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cctype>


using namespace std;

// border sections
const char upperLeftCorner = '\xDA';
const char upperRightCorner = '\xBF';
const char lowerLeftCorner = '\xC0';
const char lowerRightCorner = '\xD9';
const char horizontalLine = '\xC4';
const char verticalLine = '\xB3';

struct Machine
{
    string name;
    double cost;
    int num;
};

void init(Machine []);
int menu(Machine[]);
void payment(double);

int main()
{
    Machine drink[5];
    int choice;
    double made=0;
    init(drink);
    choice=menu(drink);
    while(choice!=5)
    {
        payment(drink[choice].cost);
        made+=drink[choice].cost;
        drink[choice].num--;
        choice=menu(drink);
    }
    cout<<"Today the machine has made $"<<setprecision(2)<<fixed<<made<<endl;

    return 0;
}

void payment(double p)
{
    double pay;
    cout<<"Your drink costs $"<<setprecision(2)<<fixed<<p<<endl;
    cout<<"Enter payment: ";
    cin>>pay;
    while(pay<0||pay>1.||pay<p)
    {
        cout<<"please insert the correct amount for your drink!\n";
        cout<<"maximum payment is $1.00\n";
        cout<<"Enter payment: ";
        cin>>pay;
    }
    cout<<"Your change is: $"<<setprecision(2)<<fixed<<pay-p<<endl;
    return;
}

void init(Machine d[])
{
    ifstream infile("DrinkMachineInventory.txt");

    if(infile.fail())
    {
        cout << "Could not find the file DrinkMachineInventory.txt \n";
        cout << "Exiting the program\n";
        exit(0);
    }

    int line = 0;
    char ch;
    string word = "";

    while(!infile.eof() && !infile.fail())
    {
        word = "";
        ch = infile.get();
        while(true)
        {
            if(isdigit(ch) || ch == '\n' || infile.eof())
                break;
            else
                word += ch;
            ch = infile.get();
        }

        if(word != " " && word != "") …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The specific problem you mention comes from a missing closing brace in the RationalNumber() c'tor.

However, it is not by any means the only problem in the code. For example, the assignment operator should be something like this:

RationalNumber& RationalNumber::operator= (const RationalNumber &right)
{
    numerator = right.numerator;
    denominator = right.denominator;
    return *this;
}

For that matter, there's a logical error in the c'tor itself, which should be more like:

RationalNumber::RationalNumber(int num,int den)
{
    if(den == 0)
    {
        den = 1;
    }
    else if (den < 0)
    {
        denominator = -den;      // use the absolute of the denominator
        numerator = -num;        // and the negative of the numerator
    }
    else
    {
        numerator = num;
        denominator = den;
    }
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You need to actually instantiate a TestScores object using the non-default c'tor, which is the only place you actually throw the exception in question.

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

I would recommend two changes. First, move the input loop to before the output loop, such that you collect all of the lines before you start outputting the randomly selected lines. Second, after displaying a line, remove that given line from the vector using the single argument version of the erase() method.

int easy()
{
    vector<string> text_file;
    string quest;
    char choice;
    int line_counter = 1;
    srand(time(NULL));

    ifstream myfile ("./questions/easy.txt");
    cout << "Welcome to EASY level category!\n" << endl;

    if (myfile.is_open())
    {
        while( getline( myfile, quest ) )
        {
            text_file.push_back( quest );
            line_counter++;
        }

        while(choice != 'q')
        {
            int line = rand() % line_counter;
            cout << text_file[line];

            text_file.erase(text_file.begin() + line);
            line_counter--;

            cout << "\n\nPress [n] to proceed and [q] to quit: ";
            cin >> choice;
        }

        myfile.close();
    }

    else cout << "Unable to open file";
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I have noticed that there are some problems with the indented code posted by Captain Jake, specifically that some braces appear to be missing. I've used AStyle to automatically re-indent the code, which I hope will help make the main bug clearer:

{ 
    int quantityamount1[3];

    for(int i=0; i<3; i++)
    {
        cout<<"Enter quantity for item "<<i+1<<":\n";
        int quantity=0;
        cin>>quantity;
        if(quantity<=wh[0].amt[i] && wh[0].amt[i]>0)  //Searching current warehouse inventory

            wh[0].amt[i]-=quantity;
        quantityamount1[i]=quantity;
    }
    else
    {
        for(int j=1; j<5; j++)
        {
            if(wh[j].amt[i]>0 && quantity<=wh[j].amt[i])  //Searching other warehouses to fulfill order
            {
                cout<<quantity<<" quantity of item "<<i<<" shipped from "<<wh[j].city<<" to "<<wh[i].city<<"\n";
                wh[j].amt[i]-=quantity;
                cout<<wh[j].city<<"  "<<wh[j].amt[0]<<"  "<<wh[j].amt[1]<<"  "<<wh[j].amt[2]<<"\n";
                break;
            }
            else
            {
                cout<<"Order Unfilled\n";//Could not find any warehouses to fulfill order
                quantityamount1[i]=1;
                break;
            }
        }
        quantityamount1[i]=quantity;
    }
}

The problem lies in the else statement inside the inner for() loop; the way it is currently situated, it will end the loop prematurely. You want to take the clause out of the loop and use a separate if() statement to check whether the loop was exhausted without finding the item in any of the warehouses:

for(int j=1; j<5; j++)
        {
            if(wh[j].amt[i]>0 && quantity<=wh[j].amt[i])  //Searching other warehouses to fulfill order
            {
                cout<<quantity<<" quantity of item "<<i<<" shipped from "<<wh[j].city<<" to "<<wh[i].city<<"\n";
                wh[j].amt[i]-=quantity;
                cout<<wh[j].city<<"  "<<wh[j].amt[0]<<"  "<<wh[j].amt[1]<<"  "<<wh[j].amt[2]<<"\n";
                break;
            }
        }

        if (j >= 5)  // for loop was exhausted without finding the sought items
        {
            cout<<"Order Unfilled\n";//Could not find any warehouses to fulfill order
            quantityamount1[i]=1;
            break;
        }

As an aside: you might want to use named integer constants for …

PrimePackster commented: Thanks for pointing out +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Line 31 should be b = int(a);

I think you meant a = (int) b; , or maybe a = static_cast<int>(b); . Just saying.

EDIT: Just noticed that the variables were reversed, too. I've fixed that now.

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

While that is one of the uses of pointers, it is not the whole purpose or even the main purpose of them. Still, I'll address the question in two parts.

First, speaking of functions generally, it is better to pass an argument explicitly rather than having access to it implicitly, because it makes it clear what the function is operating on. I've already explained the reasons for this, so I won't go into them again.

More importantly, it separates the function from the data it is manipulating, allowing you to apply it to a different data structure each time it is called. This is important because it allows you to write code in a 'modular' fashion, that is, you can break a program down into separate sections and use different sections of the program repeatedly.

For example, let's take the function strcpy(), the old C-style string copy function. It takes two arguments, one for the destination array and the other for the source array. By using pointers to the arrays, the function can be applied to any two string variables, without knowing ahead of time what arrays they are or even how long they are. If you didn't have this flexibility, you'd need a separate function for copying one array to another for every two pairs of arrays you might want to copy! Whereas with pointers, you can manipulate the arrays without knowing anything but the address where they begin (and where they end, though with C-strings …

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

Actually, I think that thines01 misunderstood the project requirements; what you describe is what is called a 'shell' in the Unix/Linux world. You won't necessarily be getting command-line arguments for this program, but will be reading in a command line and executing it, then reading another command line and executing that, and so on until someone types in 'exit'.

The tricky part of a shell is not the parser, but the ability to execute another program without using the existing system() command. The functions for spawning an executing a process are system-dependent, thus how you would do it would be different under Windows than under, say, Linux. What sort of system is this meant to run under?

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

2. Why use pointers when the array can be declared as global?

I assume you're talking about passing arrays to functions, in which case the answer is, because global variables in general are a Bad Thing, or at least enough of a bad thing that you will want to use them sparingly if at all. Now, admittedly, this leaves out a bit of explanation, but the real issues has to do with visibility, namespace pollution, and uncontrolled access of global data. If that doesn't help, I'll try to explain a bit more.

First off, when you make a global variable, you take up a part of the global namespace. In a large program, if you have a lot of globals, sooner or later you (or some other programmer you're working with) are going to lose track of what names have already been used, and get a namespace collision - that is, you'll declare two different variables with the same name, and then wonder why a part of the program that was working fine before suddenly broke. Even if you manage to avoid this, you most likely will end up having to use awkward work-arounds in order to avoid repeating names. It is easier all around to limit as many variables as possible to local scope, which means that if you want to share them with other functions, you need to pass them to those functions as arguments.

The second part of this is related to the first, which …

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

About half of these are warnings rather than errors (mostly ones relating to standard functions Microsoft considers 'deprecated', which in this case means, "Don't use the standard version, use this spiffy safer new version that happens to lock you into our compiler"). The main reason they appear at all is because you are using the older versions of the header files (e.g., <stdio.h> and <fstream.h> rather than <cstdio> and <fstream> ), which are deprecated (and not just by MS this time). While the newer headers do, in fact, contain the standard functions in question, they are 'grandfathered in', whereas the versions from the any other headers (even the old 'standard' headers) are not.

Anyway, most of these errors will go away once you fix <fstream> . The rest are mostly tied to the (unequivocally non-standard) "simpio.h" , which, given that you are also include <stdio.h> (which, as I said, should be <cstdio> now), is probably completely unnecessary (and did I mention non-standard?).

Oh, if you're serious about getting another compiler, I would look into Code::Blocks, a fairly good IDE which comes with the MinGW port of GCC. The bad news is the debugger, which is awful; but then again, the only really good debugger for C++ under Windows is, in fact, the one that comes with Visual C++. Sorry about that.

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

I just notice that Hp1 and Hp1base are reversed in all of those cases.

void Heal()
{
    Hp1 += 100;
    // if the increase goes over the HP max, adjust to the max
    if ( Hp1 > Hp1base )
    {
        Hp1 = Hp1base;
    }

    Mana1 += 50;
    // if the increase goes over the Mana max, adjust to the max
    if ( Mana1 > Mana1base )
    {
        Mana1 = Mana1base;
    }
}

I'll also repeat my earlier suggestion of making a class to represent the Hero characters in the abstract, rather than having a separate AI Hero with completely different, redundant functions. A simple sketch of the class definition might be:

class Hero
{
public:
    Hero(string name, int str, int intel, int agil, int hp, int mana, int armor);

    //
    void NormalAttack();
    void Choice();
    void Attack();
    void Skill();
    void Defend();
    int Run();
    void Heal();
    
    // accessors
    int getStrength();
    int getIntelligence();
    int getAgility();

private:
    unsigned strength, intelligence, agility;
    int currentHp, baseHp;
    int currentMana, baseMana;
    int currentArmor, baseArmor;
};
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Still not solved. Hm..

How is it behaving now? What is it doing wrong, or not doing right?

sorry if i used the name of heroes in warcraft.we'll change it because our project is text-based dota

Hey, I figure that's between you and Blizzard. I just found it amusing.

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

I agree with Pseudorandom21 on both of these points, especially the latter: when I tested the code myself (using GCC 4.4.1 running through Code::Blocks 10.5 for Windows), I found that the program would hang and crash until I changed that particular loop to test for end-of-file.

As for the box characters, this chart shows the ones in use in US PC systems. Note that it is completely non-portable and may not work consistently even on PCs.

EDIT: I just tried these codes, and they did not work in the default codepage that Windows pops up when running from Code::Blocks. I'll continue looking for information on this, but I can't promise that you'll ever get consistent results.

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

I'm guessing that the easiest solution involves recursion, and specifically that it is closely related to the integer-to-string algorithm: you accumulate the changes on the stack and rejoin them as the function calls return.

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

In the MazeConstructor class, you define a method named Nodes() (not the plural), but you never implement it anywhere. I suspect that what you actually want is the constructor for the Node class, however, which you do define (though incorrectly, I think - the data argument should be a string, not a single character).

On an unrelated note, I think you will want to change the definition of the nodes[] array to

Node * nodes[12];

This is because the individual elements of nodes[] has to hold a pointer to a Node , rather than a Node object. An even better solution might be to use a vector :

vector<Node*> nodes;

This takes away the size limit on the number of Node pointers.

I would also recommend separating the file into separate header and implementation files for the different classes, as this will make it much, much easier to read and reason about. You will need to have all of the different files together in a single Makefile or Project, depending on just what IDE and compiler you're using, but this isn't a very difficult process. For example, I'd previously taken earlier version of the Node class and broke it into a MazeNode.h header file and a MazeNode.cpp implementation file:

MazeNode.h

#ifndef MAZE_NODE_H
#define MAZE_NODE_H

#include <string>

class Node
{
private:
    std::string name;
    Node* north;
    Node* south;
    Node* east;
    Node* west;

public:
    Node(std::string n = " ");

    Node* GetNorth() { return north; };
    Node* GetSouth() …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I've realized since posting that that you didn't intend for those functions to be part of info ; sorry if I confused you in any way.

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

To address the last (non-)question first, you could use the predicates from <cctype> to check the characters if you really needed to. You'd probably have to check against a few different things to get exactly the character set you were looking for.

On a side note, with a modern C++ compiler, you want to use <cstring> rather than <string.h> . Just something to note for the future.

A second side note: #pragma statements are compiler-specific, and the once pragma in particular is specific to Visual C++ and GCC. While I don't believe it causes any warnings to come up under other compilers, it also won't have any effect under most of them, either. The usual solution to the multiple inclusion problem is to use include guards, instead. (It's not a big deal, but you should be aware of it.)

A further side note would be that you should separate the declarations of your class member functions from the implementation, preferably in different files, except for very simple (one or two line) functions. This does mean that you'd need to link in the *.cpp files to your main.cpp program file when you go to compile the program, but this shouldn't be difficult. This would give you the following files:

info.h

#pragma once

#define nullptr 0

class info
{
public:
    bool eof;
    bool good;
    bool fail;
    bool bad;
    char r;

    static info getNextChar(char* to);//read the next char in binary form.
    static …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As an aside: you might want to use named integer constant for the number of characters you're reading in, rather than using a magic number the way you are now. It would make reading and changing the program easier, and it is a good habit to get into. For example, instad of what you have now, you could have written:

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cstdio>
#include<cstring>

using namespace std;

const int LINE_SIZE = 80;

int main()
{
    ifstream inFile ("d:/Text1.txt", ios::in);
    char sentence[LINE_SIZE];

    if(!inFile)
    {
        cerr<<"File Text1.txt could not be opened"<<endl;
        exit(1);
    }

    inFile.getline(sentence, LINE_SIZE);

    cout<<endl;
    cout<<"The file Text1.txt contains the following sentence:";
    cout<<endl;
    cout<<sentence;
    inFile.close();
    cout<<endl;

    cout<<"Please enter a lowercase letter between (a-z):";
    char letter;
    cin>> letter;

    return 0;
}

(Note also the use of the code-tags, which allows the formatting of the code to be retained. You should always post you code with code tags on this forum.)

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

The best way to do it is to have an integer variable, initialized to zero, which will hold the number of times the letter appears. You would then have a for() loop going from 0 to 79 (that is, it would continue while the index would be less than 80), and inside the loop you would have a conditional comparing the current array element in sentence to the letter . If the two characters match, then you would increment (add one to) the counter variable.

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

Just curious, I had tried your code and I got "usage: rainfall <current_datafile> <previous_datafile> <output_file>

Process returned 255 (0xFF) execution time : 0.003 s
Press ENTER to continue."

What exactly is going on there?

The version of the program I wrote requires command-line arguments. If you are using Code::Blocks (which I gather is the case), you can go to the Project menu and select Set Programs' Arguments to add the filenames: rainfall_current.dat rainfall_previous.dat rainfall_totals.dat When this is run, it should create a file named rainfall_totals.dat which will contain the generated tables.

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

Probably the easiest way to convert an integer to a string is by using a stringstream:

int five = 5;

string mystring;
stringstream ss;

ss << five;

ss >> mystring;

A slightly different take on this can be found here; which is better for you depends on what you find convenient.

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

How are the boxes defined in the program? Or is that part of what you need help with?

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

The problem is that, unless you define them yourself, there are no comparison operators for the Date type. The compiler does not know how to compare one Date value with another.

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

The error messages are fairly straightforward: most of the member functions you are calling do not actually exist. You need to define and implement a constructor for Node which accepts a string as an argument, plus all of the member functions which you are using ( SetNorth() , etc).

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

For line 12, you declare counter as a reference to int . References are similar to pointers in that they do not hold a value in themselves, but instead refer to another variable. Thus, counter won't work unless you assign a reference to it.

I suspect that for counter (and overall ) what you actually wanted to do was declare it as static , which makes a variable that is shared between all of the instances of the structure.

For line 14, you cannot have you cannot have an initializer inside of a struct , and in any case, you cannot have a non-constant initializer.

BTW, have you studied classes at all yet? The main differences between a struct and a class are a) class members are private by default, while structure members are public by default, and b) structures cannot inherit from other structures or classes. However, by convention you normally would use a class for something that has member functions, even though structures can have them as well.

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

The order of the tests is reversed; you want to increment the base amount first, then check whether it is over the maximum after the values have been increased.

void Heal()
{
     Hp1base += 100;
     // if the increase goes over the HP max, adjust to the max
     if ( Hp1base > Hp1 )
     {
          Hp1base = Hp1;
     }

     Mana1base += 50;
     // if the increase goes over the Mana max, adjust to the max 
     if ( Mana1base > Mana1 )
     {
        Mana1base = Mana1;
     }
}

I don't know how advanced you are in C++ yet, but I would suggest making a Hero class, which you can then instantiate for the individual characters, rather than repeating (more or less) the same code for the player's hero and the AI hero.

As an aside, you might want to change the name of the game to something that isn't already copyrighted :P

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

Another side issue I notice while going through the code: you have the following line of code

unsigned int srand = time(0);

However, srand() is a function, which this variable is masking; the result is that the randomizer never actually gets initialized. Also, you only need call srand() once, at the beginning of the program.

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

As a side issue, why didn't you define the border functions using a for() loop? It would be a lot easier to read and change, if you needed to:

const int LINE_LENGTH = 75;

// ...

void borderDown() 
{
    const char o = 209;

    for (int i = 0; i < LINE_LENGTH; i++)
        cout << o;
    cout << endl << "		";
}

void borderUp()
{
    const char o = 207;

    for (int i = 0; i < LINE_LENGTH; i++)
        cout << o;
    cout << endl;
}

I tested this and it appeared to work the same as the original, so why not do it this way to begin with?

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

The linker isn't losing track of things; the problem lies in the header, and more specifically, the function prototypes for those two functions. The prototypes are declared as:

void clearBoard(int, char);
void printBoard (char, int);

Whereas the functions themselves are actually:

void clearBoard(int, char*[]);
void printBoard (char*[], int);

This is one place where (IMAO) using fully-qualified function prototypes would help, as it would be clearer where the difference lies:

void clearBoard(int size, char *board[]);
void printBoard(char *board[], int size);
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, passing the filenames by command line might be the best solution of all:

/*
File: Rainfall.cpp
Description: Write a program that reads in the average monthly rainfall for a city for each month
of the year and then reads in the actual monthly rainfall for each of the previous 12 months. The program
then prints out a nicely formnatted table showing the rainfall for each of the previous 12 months as well
as how much below or above average the rainfall was for each month. The average monthly rainfall is given
for months January-December in order. To obtain the actual rainfall for the previous 12 months, the program first
asks what the current month is and then asks for the rainfall figures for the previous 12 months.

After you have completed this program, produce an enhanced version that also outputs a graph showing the
acerage rainfall and the actual rainfall for each of the previous 12 months. Your program should also ask the
user whether they want to see the table or the graph. Include a loop that allows the user tos eee either format as
many times as they wish until they end the program.
*/

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
#include<cmath>

using namespace std;

// Gives the array strings for each of the 12 months. Sets a constant array.
const string Month[12]= {"January", "February", "March",
                         "April", "May", "June",
                         "July", "August", "September",
                         "October", "November", "December"
                        };


// Precondition: Declares the arrays for the current and previous data. …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you please tell us what is it doing? What should it do that it is not?

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

I believe that at least one part of the problem can be fixed by changing the function prototype such that nbrCells is a const long reference rather than just a long :

template <class T> int getVectort(ifstream & s,
                                  const long & nbrCells,
                                  typename vector<T>::iterator iter)

This will allow for either a plain long argument or a const long argument; since DEMOD_NBR_INPUTS is, presumably, a const long , this will eliminate at least part of the problem, while also adding a check that nbrCells isn't being changed (which should be the case).

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

Actually, there is one more means of repetition, called recursion, but most C++ programmers consider recursive functions to be both too confusing and too inefficient to be used regularly. Being a Lisp programmer, I find this attitude silly, but there it is. :P

Recursion consists of writing a function that calls itself, with a test somewhere in the function to determine when to stop. A basic example of a recursive function would be the Euclid's Greatest Common Divisor algorithm:

int recursive_gcd(int a, int b)
{
    if (b == 0)
        return a;
    else
        return recursive_gcd(b, a % b);  // '%' is the 'modulo' (or 'remainder') operator
}

This can be compared to the iterative version of the same algorithm, which uses a while() loop to perform the repetition:

int iterative_gcd(int a, int b)
{
    int swap;

    while (b != 0)
    {
       swap = b;
       b = a % b;
       a = swap;
    }

    return a;
}

I don't know if this helps you or confuses you more, but I hope that it does at least explain something.

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

This may be a bit advanced of a suggestion, depending on just how the professor is teaching the course, but: one way to improve the readability of the code would be to use an enumeration for the three different states rather than using numbers for them. Combining this with the previous suggestions would give the following example:

enum PLAY {ROCK, PAPER, SCISSORS};

// ...

PLAY getUserPlay()
{
    char userpick;
    PLAY userplay; 

    cout<<"Pick either (R)ock,(P)aper, or (S)cissors. \n";
    cin>>userpick;
    userpick = toupper(userpick);

    if(userpick=='R'){
        userplay = ROCK;
        cout<<"so you picked rock";
    }
    else if(userpick=='P'){
        userplay = PAPER;
        cout<<"so you picked paper";
    }
    else if(userpick=='S'){
        userplay = SCISSORS;
        cout<<"so you picked scissors";
    }

    return userplay;
}

This makes a nicely readable and concise function which you can use to get the player's choice.

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

Is

double (*func)();

a function pointer?

Yes, though by C++ standards, the typing is incomplete.

GCC supports a lot of things without a warning, but it gives me one when I use standard C++0x features for some reason :D

I'm pretty sure that GCC defaults to the C++98 standard, as the C++11 standard wasn't actually formalized until a little over a month ago (hence the 'x' in the older working name of the standards group). The GCC development team treat C++11 as 'experimental', as they are still working on the new features and aren't entirely compliant with it yet.