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

I realize that I may be overreaching myself, but to save everyone trouble, I've converted the code for the OP:

#include <cstdio>
#include <cmath>
#define pi 3.141593
#define F(x) ((*f)(x))
#define sqr(x) ((x)*(x))
#define no_intv 5000

double xsav;
double (*nrfunc)(double x, double y);

double ellip2d(double a, double b, double (*func)(double x, double y));
double f1(double s1);
double f1(double s1);
double f2(double s2);
double funcn(double x, double y);
double simpson(double a, double b, double (*f)(double x));

int main()
{
    double Nq;
    Nq = ellip2d(-pi, pi, funcn);

    printf("Nq = %f\n", Nq);

    return 0;
}
//////////////////////////////////////

double ellip2d(double a, double b, double (*func)(double x, double y))
{
    nrfunc = func;
    return simpson(a, b, f1);
}

double f1(double s1)
{
    xsav = s1;
    return simpson(-pi, pi, f2);
}

double f2(double s2)
{
    return ((*nrfunc)(xsav,s2));
}

////////////////////////////////////
double funcn(double x, double y)
{
    return x * x + y;
}

double simpson(double a, double b, double (*f)(double x))
{
    int i;
    double x,h,sum = 0.0;
    if(fabs(b-a) < 0.000001) return 0.0;
    h = (b - a) / ((float)no_intv);
    x = a + h;
    for(i = 2; i <= no_intv; i++)
    {
        if(i&1) sum += 2.0 * F(x);
        else    sum += 4.0 * F(x);
        x+=h;
    }
    return (h*(F(a)+sum+F(b))/3.0);
}

This is just a straight translation; since Physicist presumably knows what changes he wants to make, I'll leave it to him to convert the I/O and so forth.

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

Surprisingly, it is actually valid C, or rather, it was valid about twenty-five years ago. The function argument declarations are of a form that was used in 1st edition K&R C, but which most modern compilers wouldn't accept as far as I am aware (though interestingly, GCC accepts it without even a warning). The same applies to the function prototypes.

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

I'll admit that I've probably gone too far.

Kjcjk, however, is the OP, so he has reason to be posting the code he's trying to fix.

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

Getting back to the original question, the code below fixes most of the syntactic errors in the code, though I did not attempt to correct the logical flaws without a clearer idea of the intended behavior:

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

using namespace std;

const int ARRAY_SIZE = 100;

void InputData(string[], int[], int &);
void DisplayPlayerData(const string[], const int[], int);
double CalculateAverageScore(const int[], int);
void DisplayBelowAverage( const string[], const int[], int, double);

int main()
{
//Declare the player name and score arrays, number of players, and average score.
    string playerNameAr[ARRAY_SIZE];
    int scoreAr[ARRAY_SIZE];
    int numPlayersAr = 0;
    double averageScore;

    cout << fixed << showpoint << setprecision(2);

    //Call the InputData function
    InputData(playerNameAr, scoreAr, numPlayersAr);
    //Call the DisplayPlayerData function
    DisplayPlayerData(playerNameAr, scoreAr, numPlayersAr);
    //Call the CalculateAverageScore function and assign the returned value in average score
    averageScore = CalculateAverageScore(scoreAr, numPlayersAr);
    //Call the DisplayBelowAverage function
    DisplayBelowAverage(playerNameAr, scoreAr, numPlayersAr, averageScore);

    return 0;
}


void InputData(string playerNameAr[], int scoreAr[], int & numPlayersRef)
{
    while(numPlayersRef < ARRAY_SIZE)
    {
        //Prompt for the player's name or Q to quit
        cout << "Enter the player's name (Q to quit). " << endl;
        getline (cin, playerNameAr[numPlayersRef]);
        if (playerNameAr[numPlayersRef] == "Q") break;
        //Prompt the user for the player's score
        cout << "Enter the player's score. " << endl;
        cin >> scoreAr[numPlayersRef];
        //Add 1 to the number of players
        numPlayersRef++;
    }
}

void DisplayPlayerData(const string playerNameAr[], const int scoreAr[], int numPlayers)
{
    cout << setw(10) << left << "\n Name"
         << setw(5) << right << "Score" << endl;
    for(int i = …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While it is not the only problem with the code, the main issue is that you are using an output file for input. You will want to change the program thusly:

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

const int LinesToPrint = 10;

using namespace std;

int main()
{
    ifstream inputfile;
    string line;
    int lines=0,i=0;
    char c;
    inputfile.open("newfile.txt");
    while (getline(cin,line))   //I copy each line of the file to the file I created
    {
        inputfile >>line;  //I put endl because I don't know if '\n' is
        lines++;                 //included in getline
    }
    if (lines==0)
    {
        cout<<"Den upirxe eisodos!"<<endl;  //if the file was empty I print a
    }                                            //message saying that
    else if (lines<=10)
    {
        cout<<inputfile<<endl;  //if there are 10 lines or less I print it
    }
    else
    {
        while (inputfile.get(c))  //my problem is here!!! I also tried to use
        {
            //getline but I had the same problem as now
            if ((c=='\n')&&(i!=lines-LinesToPrint+1))
            {
                i++;
            }
            if (i==lines-LinesToPrint)
            {
                i++;
                continue;
            }
            if (i>lines-LinesToPrint)
            {
                cout<<c;
            }
        }
    }
    inputfile.close();
    return 0;
}

This doesn't actually work, as of now, but it will at least compile. If you need more help debugging this, let us know.

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

OK, this code here should solve that issue:

int getInput()     //get user's number guess
{
    int numGuess = 0;
    while (numGuess == 0)
    {
        cin >> numGuess;
        if (cin.fail())
        {
            cout << "Please enter a number: ";
        }
        cin.clear();
        cin.ignore();
    }

    return numGuess;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What seems to be happening here is that you are getting a conflict between two variables named coeff : one is an instance variable of the class, which is an array of int , the other is an argument of the method, which is an int . Because of the scoping rules, the argument is masking the instance variable.

You need to either a) rename the argument to something other than coeff , or b) use this->coeff[] when referring to the instance variable. I would recommend the former, as having two variables of the same name is still likely to cause confusion even when using this to avoid ambiguity.

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

Try the following code:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

bool check (int numOne, int tries, int numGuess);
bool validate (int input);
int getInput();

int main ()
{
    int tries, input;
    char yesNo = 'Y';
    srand(time(0));

    while(toupper(yesNo) == 'Y')
    {
        int numOne = (rand()%100) + 1; //seed computer's number
        tries = 0;
        input = 101;

        cout << "I have a decimal integer between 1 and 100." << endl << "Can you guess it? ";

        do
        {
            do
            {
                input = getInput();
            }
            while (!validate(input));

            tries++;
        }
        while ((tries < 9) && !(check(numOne, tries, input)));

        if (tries == 9)
            cout << "Sorry, you ran out of guesses." << endl << endl;

        cout << "Play again (Y/N)? ";
        cin >> yesNo;
        cin.ignore();
    }

    return 0;
}

int getInput()     //get users number guess
{
    int numGuess = 0;
    cin >> numGuess;
    cin.ignore();
    return numGuess;
}

bool validate (int input)
{
    if (input < 1 || input > 100)
    {
        cout << "Please enter a decimal integer between 1 and 100: ";
        return false;
    }
    return true;
}

bool check (int numOne, int tries, int numGuess)
{

    if (numGuess > numOne)
    {
        cout << "Too high, Try again! " << endl;
        return false;
    }
    else if (numGuess < numOne)
    {
        cout << "Too low, Try again! " << endl;
        return false;
    }
    else
    {
        cout << "You guessed it! " << "It only took you " << tries << " tries!" << endl;
        return true;
    }

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

I realize that you may not have a choice in this, but I would recommend upgrading to a newer compiler if you can. Turbo C++ 4.5 is now over 15 years old, and it is still primarily a DOS compiler if I recall correctly. I'm not sure if it will work with Windows 7 at all (I know that older versions of Turbo C++ do not). More importantly, it is based on an earlier version of the C++ language, and does not work correctly with the current header files, and the current namespace system.

There are several good, freely available compilers and IDEs, such as Code::Blocks (which is based on the well-known GCC compiler) or Visual C++ Express. Not only are these modern, Windows-based compilers and IDEs, both support a version of the _getcwd() function (not a C++ standard function, it is system-dependent, but both have libraries containing it), which is exactly what you are looking for.

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

As much as I personally like recursive approaches, recursing on main() is generally considered a Bad Thing. The main() function is different from others; while it is possible to call it, doing so is problematic. A more conventional approach would be:

int main (){
    char yesNo = 'Y';
    srand(time(0));

    while(toupper(yesNo) == 'Y') 
    {
        int numOne = (rand()%100) + 1; //seed computer's number
        int tries = 0;
        int input;
        cout << numOne << endl; // used for checking program.

        cout << "I have a decimal integer between 1 and 100." << endl << "Can you guess it? ";
        input = getInput();
        while(validate(input)){   //while number is valid (1-100)
             check(numOne, tries, input); //continue with program
        }
        cout << "Continue (Y/N)? ";
        cin >> yesNo;
        cin.ignore();
     }

    return 0;
}

I could add that validate() is still problematic; it is declared as type bool , but returns NULL rather than either true or false , and the result doesn't vary. The sum effect of this is that the line

while(validate(input)){

always evaluates as false, meaning that the program never enters the loop in the first place.

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

I've gone back to my version of the original algorithm:

double SimpsonArea (int n, int* yValue, double length)
{
    double sum = 0, deltaX;

    for(int i = 0; i < n; i++)
    {
        if ((i == 0) || (i == (n - 1)))
            sum += yValue[i] * 4.0;
        else
            sum += yValue[i];
    }

    deltaX = length / (n - 1);
    return deltaX * sum;
}

... and I'm having trouble seeing where the problem lies. Can you give us the original description of the algorithm that the professor gave you to use?

(Oh, and I simplified the testing process by re-writing the main() function to read the data from a CSV file; I can pass that along as well if you'd like.)

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

Try this:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

const int GEARS = 15;

int toTwoDigitTime(char a, char b)
{
    int tens = (a - 0x30) * 10;
    int ones = (b - 0x30);
    return tens + ones;
}


/** Showing the introduction screen and the user manual... */
void splash(void)
{
    cout << "   ********************************************************\n";
    cout << "   *                                                      *\n";
    cout << "   *            Velocity And Gear Programme ..            * \n";
    cout << "   *         By:****                                      *\n";
    cout << "   *                                                      *\n";
    cout << "   ********************************************************\n\n";

    cout<<endl ;
    system ("PAUSE");
    system ("cls");
    cout << "****************************************************************\n";
    cout << "*               USER MANUAL                                    *\n";
    cout << "* FIRST : The programme will ask you to input the acceleration * \n";
    cout << "* SECOND: The programme will ask you to input the time         *\n";
    cout << "* THIRD : The programe will calculate the velocity             *\n";
    cout << "****************************************************************\n\n";

    system ("PAUSE");
    system ("cls");
}
/** Showing the introduction screen and the user manual... */

double Velocity(double accel, double ntime)// to calcluate the Volcity
{
    return accel * ntime;
}

int main ()
{
    double accel;
    char choice;
    string time;
    double h = 0, m = 0, s = 0;
    splash();

    do
    {
        cout<<"What was your acceleration in (km/hour):  ";
        cin>>accel;
        cin.ignore();
        cout<<"\nWhat was your riding time in hr.min: ";
        cin >> time;
        cin.ignore();

        if (!(isdigit(time[0]) && isdigit(time[1]) &&
                isdigit(time[3]) && isdigit(time[4]) &&
                isdigit(time[6]) && isdigit(time[7])))
        {
            cout << "Your time is invalid" << endl;
            break;
        }

        h = toTwoDigitTime(time[0], …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There are a number of issues with this code that I can see, with the foremost being with the way you are getting the time. As it is, you are reading in the time as an 8-character array, using gets() (which is deprecated as being unsafe, but that that's a side issue), then using three of the numerals read in (assuming their positions are correct) as if they were integers. This simply will not work as you're expecting it to.

I can also recommend simplifying the code for showing the velocity and the gear by using a lookup table for the gear ranges.

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

The first thing I recommend is that, in order to simplify reasoning about the Simpson's Rule function, you should move the part that gathers the elevation data from the function proper, storing the data in an array which you can then pass to the function. You'll need to allocate the array before using it, and delete it after you've finished with it, but this isn't too serious a problem.

Second, I would look at the example implementation on the Wikipedia page about Simpson's Rule, as it may clarify just how the rule normally works.

I have tried to apply both of these suggestions myself, but the function is still not quite correct. Nonetheless, I think that this altered code may help you in working out the correct method.

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

// Prototypes
double SimpsonArea(int, int*, double);

int main()
{
    int NumPoints, RdWidth;
    double RdLength, HillCrossSectionalArea, DirtVolume;
    char Usrp;

    do
    {
        cout << "\n\n";

        cout <<"\nEnter the length of roadway through the hill:";
        cin >> RdLength;
        cout <<"\n      Enter the width of the roadway:";
        cin >> RdWidth;
        cout <<"\nEnter the number of points at which hill";
        cout <<"\n          elevation was measured:";
        cin >> NumPoints;
        cout <<"\nEnter the hill elevations(y values) at the";
        cout <<endl << NumPoints << " equally-spaced points:";
        cout <<"\n\n";

        int *yValues = new int[NumPoints];

        for(int i = 0; i < NumPoints; i++)
        {
            cout <<"Enter y value #" <<i+1 <<":";
            cin >> yValues[i];
        }

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

Correct. tries is changed in another function. If the user does not input a valid number it will ask for another number until a valid number is inputted, i.e. an infinite loop by design.

Yes, but the other function would never be called in this code as it is, thus the loop could not be broken.

Could you post this other code, so we can see what's going on in the big picture?

Also both the return values are checked elsewhere as well.

That may be, but if they always return the same value (zero in both cases), then what is there to be checked?

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

While I am not certain why it appears to be bypassing the input, I can tell you why it is going into an infinite loop: at no point do you change or test tries , which means that if the input is not a valid number in the right range, it will keep calling getInput() recursively until the stack runs out.

I could add that you do not as of this code check the return value of validate() , and getInput() always returns zero. I suspect you intended something more like this:

int getInput(int tries){
    int numGuess = 0;
    cin >> numGuess;
    cin.ignore();
    return validate(numGuess, tries);
}

int validate (int input, int tries){

    if (input < 1 || input > 100){
        cout << "Please enter a decimal integer between 1 and 100: ";
        tries--;
        if (tries <= 0)
            return 0;
        else 
            return getInput(tries);
    }
    else
        return input;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

From the thread title, I assume you are a Java or C# programmer. The main() in C++ works very differently from the equivalent in Java, being a bare function not associated with a class. You would write a main() function something like this:

int main()
{
    // code goes here
}

You usually would have it in a separate file from any classes you'd write, though that isn't necessary.

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

For those sections where you want spaces instead of zeros, simply use setfill(' ') .

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

You can use the combination of setw() and setfill('0') .

cout << setw(2) << setfill('0') << day;
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

c++ doesn't support argv[0].

That shouldn't be the case, even for Turbo C++. Can you post a) the error message you're getting, and b) the main() function you're using.

In order to use the command-line arguments, you need to define the arguments in the main() function declaration, like so:

int main(int argc, char* argv[])
{
    // main function goes here

    return 0;
}

The argc argument holds the number of arguments passed to the program, while argv[] is an array of C-style strings which holds the separate arguments.


Note the use of the int return type for main() . This is actually the correct, standard return value, and according to Stroustrup, the C++ standard never allowed for void main() in compliant code. Just be aware of this for the future.

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

I'm not sure about e , but for d , you will want to use the modulo operator, % .

For e , as I said I'm not sure, but I think it has to do with integer division by 5.

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

Actually, given that you are not initializing c , this is pretty much what you would expect to see, as the result of dividing 0 by 1.0 is in fact zero.

In order to get a different value for c , you'll want to initialize it when you declare it:

Rational c(3, 4);    // three-fourths

Or else, add setters to change the numerator and denominator after the fact.

Actually, you should be getting NaN (Not a Number), for the second part, as you never initialize d and x at all. Those two instance variables are redundant, in any case; you want to remove those two variables outright, and divide numerator by denominator :

cout << numerator / static_cast<double>( denominator ); // prints as a double number
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The issue is not with the header files, per se, but with the object files that the compiler produces before linking. You need to have the compiled object files linked together in the final version of the program, which (depending on how you are doing things) means having them together on the command line, or in a Makefile, or (most likely) in a project file of some sort. Just how you would proceed will depend on which compiler and/or IDE you're using.

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

You may want to look at the answers given here, as many (if not most) of the same issues were addressed there, for the exact same problem set.

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

In the definition of the Weapon structure, the first letter of the Name member is capitalized. In the code referring to it, the first letter is lowercase ( name instead of Name ). It's the sort of mistake anyone could make, and would have been easy to find except that the compiler error message wasn't very clear.

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

can you help?. i know some coding

Certainly I can help, as can several others here. However, writing the code for you would not be Help, it would be Cheating. No one here will help you do that.

We are willing to do quite a bit here, perhaps more than is really called for sometimes; but **you **need to show some initiative first. Post whatever code you have for this (using CODE tags, please), and we can give you advice on it.

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

As is explained here, the maximum value for rand() (defined as RAND_MAX ) is implementation defined, but is at least 32767 for a compliant compiler and library.

As for how to get the specific range you want, you need to use a combination of modulo ( % ) and addition or subtraction. So, for a range of (say) 32,000 to 33,000, you would want a range size of 1000 and an offset of 32,000:

random = (rand() % 1000) + 32000;

Different ranges and offset can be easily selected from this basic pattern.

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

Sure. The main change I made was that both front and rear are adjusted using the modulo operator whenever they are incremented, such that the values wrap around back to zero when they reach SIZE - 1 . The result is that the queue acts as if it were a ring, rather than a flat array. Thus, if you have the queue

| 1 | 2 | 3 | 4 | 5 |
  ^               ^
  |               |
front           rear

And then remove the first element, you get the queue

| 0 | 2 | 3 | 4 | 5 |
      ^           ^
      |           |
    front        rear

If you then insert a value of 6, you get

| 6 | 2 | 3 | 4 | 5 |
  ^   ^
  |   |
rear front

However, printing out the result (using the new << operator I added) gives

2, 3, 4, 5, 6

This is because the display() function was changed so that the index is relative to the value of front , and modulo SIZE as well.

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

You'll need to give us some idea of what you've tried yourself already. No one in this forum is going to do your homework for you.

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

What do you need help with? What have you been able to do so far? Do you know the syntax for declaring classes, for inheritance, for invoking a method, etc?

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

As it happens, the ones I mentioned are all portable frameworks, and can be used on Windows and MacOS as well as Linux.

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

There are several libraries available for Linux, some of which I can assure are already installed and others are easily installed from Synaptic. Examples I can think of off the top of my head include GTK+, WxWidgets, and Qt.

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

As I suspected, the declaration for Weapon is missing the semi-colon at the end (line 30).

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

Ah, that helps quite a bit. The problem is very likely to be in the header files, rather than the using directive itself. It is probably from omitting the semicolon after the declaration of the classes. Can you post Weapon.h and Room.h for us?

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

Could you tell us more about the error in question?

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

I gather your intention is to have a ring buffer queue, correct? I think that this solves most of the problems you are having:

#include <iostream>

const int SIZE = 6;


class queue
{
private:
    int a[SIZE + 1];
    int front;
    int rear;
public:
    queue();
    ~queue();
    bool insert(int i);
    int remove();
    bool isempty();
    bool isfull();
    int display(int n);
    friend std::ostream& operator<<(std::ostream& os, queue& q);
};

queue::queue()
{
    front=0;
    rear=0;
}
queue::~queue()
{

}
bool queue::insert(int i)
{
    if(isfull())
    {
        return false;
    }
    a[rear] = i;
    rear = (rear + 1) % SIZE;
    return true;
}
int queue::remove()
{
    if(isempty())
    {
        return 0;
    }
    int current = a[front];
    a[front] = 0;
    front = (front + 1) % SIZE;

    return(current);
}

bool queue::isempty()
{
    if(front == rear)
        return true;
    else
        return false;
}

bool queue::isfull()
{
    if(rear == (front + SIZE - 1) % SIZE)
        return true;
    else
        return false;
}

int queue::display( int n )
{
    int i = a[(front + n) % SIZE ];
    return i;
}


std::ostream& operator<<(std::ostream& os, queue& q)
{
    for (int n = 0; n < SIZE - 2; n++)
    {
        os << q.display(n) << ", ";
    }

    os << q.display(SIZE - 2);

    return os;
}


int main()
{

    queue q;
    int item;

    while (true)
    {
        if (q.isfull())
        {
            char answer;
            std::cout << "The queue is full. Do you want to remove an element(Y/N)? ";
            std::cin >> answer;
            std::cin.ignore();
            if (toupper(answer) == 'Y')
            {
                int top = q.remove();
                std::cout << "You have removed " << …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A few notes:

  • Yes, you would need the <cctype> header for tolower() . I could add that you'd want to also have the <cstdlib> header for the calls to system() .
  • Are the system() calls actually needed? If I am not mistaken, Visual Studio 2010 automatically pauses console programs at the end.
  • As things now are, you are opening the same file for both input and output. This means that you'll be overwriting the cleartext with the ciphertext. Given that you neither read from nor write to the file, this won't matter right now, but surely you intend to use different files for this purpose?
  • You have the path to the input file hard-coded to a specific location on your drive, which will surely present a problem when you hand the assignment in. A better solution to both this problem and the previous one would be to prompt the user for the names of the files, or else get them at the command line.
  • You have three function prototypes in your comments, but the neither the prototypes nor the functions themselves are in the code. I assume that this was part of the assignment description, which you might want to re-read.
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You can, I think, replace all three of the getevel*_symptoms() functions with a single table-driven function, something like this:

void get_symptoms(Patient* pat)
{
    char symptom;
    string queries[] = {
        "FREQUENCY OF THIRST(H(HIGH),/L(LOW)/N(NORMAL)",
        "FREQUENCY OF URINATION(H(HIGH),/L(LOW),/N(NORMAL)",
        "VISION (I(IMPAIRMENT),/N(NORMAL)",
        "URINE SUGAR(P(PASSIVE)/A(ACTIVE)",
        "KETONUREA(P(PASSIVE)/A(ACTIVE)",
        "FASTING BLOOD SUGAR(H(HIGH)/L(LOW)/N(NORMAL)",
        "R B S (H(HIGH)/L(LOW)/N(NORMAL)",
        "FAMILY HISTORY OF DIABETES(P(PASSIVE)/A(ACTIVE)",
        "OGTT(D/N)",
        "** Medical History **",
        "PANCREATITIS(P/A)",
        "CARCINOMA(P/A)",
        "CIRHHOSIS(P/A)",
        "HCTS(H/L/N)",
        "HEPATITIS(P/A)",
        "HORMONAL DISORDER(P/A)",
        " PANCREATECTOMY(P/A)",
        "** Personal Details **",
        "AGE(young(Y)/Middle aged(M)/Elderly(E))",
        "BODY WEIGHT(normal(N)/Above normal(A)/Below normal(B)/obese)",
        "DURATION (weeks(W)/Months(M)/Years(Y))",
        "AUTO ANTIBODIES(P/A)",
        ""
    };


    clrscr();
    cout<< " *** MEDICAL DIAGONOSIS FORM *** "<<endl<<endl;

    for (int i = 0; queries[i] != ""; i++)
    {
        if (queries[i][0] == '*')
        {
            clrscr();
            cout << queries[i] << endl << endl;
        }
        else
        {
            cout << queries[i] << ": ";
            cin >> symptom;
            cin.ignore();
            pat->setSymptom(i, toupper(symptom));
        }
    }
    clrscr();
}

I designed it to make it fairly easy to split the different screens up automagically; all you need is to insert a string between the end of one screen and the beginning of the next which contains an asterisk ('*') as the first character, and the program will treat it as a new screen header.

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

What do you know about C++? Start with that.

What did your professor and/or textbook cover about C++? Did you get any instruction on using the Dev-C++ editor?

What don't you know about writing the program? Do you know how to:

  • Declare a main() function?
  • #include a header file?
  • Print out something to the console?
  • Read in user input?
  • Declare a simple variable?
  • Declare an array of values?
  • Access an element of an array?
  • Write a for() loop?
  • Add, subtract, multiply and divide two floating-point values?
  • Call a library function?

These are more or less all of the skills needed for the program in question. Which of them don't you understand, and what do you think you know about them?

Just to give you a starting point, here is a basic skeleton of a generic C++ program:

#include <iostream>

int main()
{
    // your program goes here
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As for why the program is crashing, I think I've figured it out. You declare diabetes.s as type char* , but never assign an array to it. When you try to assign the symptom information to it, it gets a segmentation fault.

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

Looking more carefully at the code, I am somewhat concerned about the way it represents the patient information and handles the screens. As it is now, you have all of the information about the patient in the class diabetes , combined with all of the handling for the input and output. Normally, you would want to separate these concerns. From an OOP perspective, this is not a very clean or object-oriented design, and it is typical of someone who hasn't really understood OO principles.

I would recommend significantly re-writing the code, with a Patient class handling the actual data and a separate set of functions for the user interface.

On a side note, I would strongly recommend using fgets instead of gets() , or better still, avoiding the C-style I/O entirely. Mixing C and C++ styles of I/O is problematic at best, and the C++ style is generally far easier to use than the C style is.

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

To begin with, please use [code] tags around your code samples. This will cause the forum software to retain the formatting for the code, making it far easier to read.

Second, using void main() is incorrect in C++. While the older standards allowed it, it was always non-portable and discouraged, and it is my understanding that the current standard forbids it outright. You should always use int main() instead.

Third, your headers are in the older format ( <iostream.h> rather than <iostream> , <stdio.h> rather than <cstdio> , etc.) This, plus the use of the <conio.h> header, implies that you are using an outdated compiler, probably Turbo C++ given where you are. I realize that this may not be something you have any control over, but you should be aware that the language has changed substantially in the twenty-two years since that compiler was released. If you have any choice in the matter, I recommend moving to a newer compiler and IDE such as Code::Blocks.

(Oh, and system() is normally found in <stdlib.h> , or <cstdlib> in modern C++, which you didn't include.)

Finally, I would strongly recommend using more descriptive variable names; most of the ones you are using don't tell us anything about what they are meant to represent.

That having been said, I have to ask, what is confusing you regarding the n and m variables? I am assuming that this is your own code, so you presumably had some …

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

If you are trying to compile this with a newer compiler, well, in the words of the great Jamie Hyneman, "There's your problem!" This code depends on a number of functions that were specific to Turbo C++, and while some are re-implemented in newer libraries, the getdate() function and the date structure are not. It would take significant work to try and bring this code up to modern standards.

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

Nikesh2014: As Narue says, you didn't actually post a question, which makes it hard to give a useful answer. What seems to be the problem?

(Aside from the fact that you are using an ancient compiler, that is. Turbo C++, I'm guessing, given how many schools seem to have standardized on it even after 20+ years. Interestingly enough, MinGW - and hence Code::Blocks - does include a <dos.h> header, but it appears to be completely different from the Turbo C++ header file.)

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

I strongly recommend that you first simplify the program thusly:

/*
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.
void read_data ( double current_data …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I agree with Rohan121212; you need to give more specifics about the program.

The answer to the question would depend on just how the end of the loop is indicated. If you are given a number of cases to enter before the loop begins, then it is fairly straightforward:

int quiz_count; 

    cout << "Number of quizzes to enter: ";
    cin >> quiz_count;
    cin.ignore();
    for (int i = 0; i < quiz_count; i++)
    {
        read_quiz();
    }

OTOH, if you don't have the number of quizzes ahead of time, a while() or do..while() loop would be better:

do 
    {
        read_quiz();

        char another_quiz;
        cout << "Enter another quiz (Y/N)? ";
        cin >> another_quiz;
        cin.ignore();
    } while (toupper(another_quiz) == 'Y');

Do either of these solve your problem?

TaoNinja commented: Helped me out ^_^ +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The signature of the function prototype for Shuffle() doesn't match that of the actual function definition. The prototype has the two parameters as reference types,

void Shuffle(int& num, char& suit);

but the function just has

void Shuffle(int num, char suit)

These are seen as being two different function signatures by the compiler, which assumes you meant to overload the function name Shuffle() but cannot disambiguate calls for the two forms.

(BTW, it is advisable to always give the full function signature - including the names of the parameters - in the prototype, rather than just the type signature, even though it isn't required. With good parameter naming, the full prototype is much more readable and tells you more about the function.)

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

Let's start by separating the algorithm from the (extraneous) output:

#include <iostream>

int gcd(int a, int b);

int main()
{
    int a, b;

    std::cout<<"Enter the A Integer: ";
    std::cin>>a;
    std::cout<<"Enter the B Integer: ";
    std::cin>>b;

    std::cout << "The Greatest Common Divisor of " << a
              << " and " << b
              << " is " << gcd(a, b);
    return 0;
}



int gcd(int a, int b)
{
    int r;

    // if a is greater than b, swap a and b
    if (a < b)
    {
        r = a;
        a = b;
        b = r;
    }

    // now perform the algorithm
    while (b != 0)
    {
        r = a % b;
        a = b;
        b = r;
    }

    return a;
}

I don't know if this helps or not, but it should make the algorithm itself show clearly. In general, you don't want to have the user input and output tnagled up in with the part of the code that performs the actual operations, if you can avoid it, as it makes it harder to understand.

There are two other points I'd like to make. First, you should indent you code to make it more readable, much like I have here. Second, the code you posted is for an older compiler, probably the ancient Turbo C++; if you have any choice in the matter, you should upgrade to a more modern compiler and IDE such as Code::Blocks or Visual C++ Express.

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

There are a number of issues which I can see with this, mostly relating to the dynamic memory allocation. Let's walk through the current workflow and it should show where the problems lie.

First, in main() , you declare pizzaPtr as an array of two pointers to type Pizza . you do not initialize this array before calling Order() with pizzaPtr as an argument.

In Order() , you are passed the pointer specPtr . Then, inside the for() loop, you re-declare specPtr , causing the argument to be masked by a local variable. This local specPtr is then initialized, set, and then discarded, with no effect being made on the argument version of specPtr .

Once back in main() , you then attempt to initialize pizzaPtr[0] with a new Pizza object, then print out the newly created Pizza object. You do the same for pizzaPtr[1] .

Does this make things a bit clearer?

I think what you will want to do is initialize the two elements of pizzaPtr before passing pizzaPtr to Order() .

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

Certainly, you can write functions that work recursively, yes. Here is your function written in just such a fashion:

#include <iostream>
#include <cctype>

using namespace std;

void repeat();

int main()
{
        repeat();
}

void repeat()
{
    char s3='n';
    cout << "Would you like to perform another operation? (Y/N)" << endl;
    cin >> s3;
    s3 = toupper(s3);
    if (s3=='Y')
    {
        repeat();
    }
}

Now, in C++, recursion often gets a bad rap for inefficiency, especially since (by default at least) C++ compilers generally don't perform tail call optimization. But it is perfectly possible to use recursion in this manner, yes.