gnarlyskim 1 Junior Poster in Training

Well it turned out that I overused the delete[] coef's to an extreme and it hurt me(contrary to what I thought). My code now runs completely in sync with the solution.exe, what a great way to finish the final project of my C++ course. Thanks to all who have helped me in these posts! Time for some drinks...after all it is Friday right?!

gnarlyskim 1 Junior Poster in Training

MrSpigot and Banfa, I deleted all of my explicitly called destructors and everything within the program that I've posted to here works perfectly. I really appreciate the time for y'all to look through and help me out.

Banfa, unfortunately simplicity is a word never associated with undergrad "weed-out" courses in school. We aren't covering vectors in the course, but in the past I've had that suggestion from a few other people on this forum, so I'll have to do some research on my own time after the course ends. As far as the for loops, I've been working on this code for a few weeks (over the course of several projects) and I initially started for loops by going through them backwards, so I implemented every loop I would use in a backwards manner. For the sake of keeping what I know works constant and "staying on the same page" conceptually with the rest of the code, I'm just going to finish this project as-is. In the future, moving forwards is always better than going backwards so I'll remember that ha. Thanks a ton though!

gnarlyskim 1 Junior Poster in Training

Sorry for the lack of information. Here's a little more that is also relevant.

As for when it crashes, it varies on occasion. I've added cout's to the overloaded definition of * before returning a value, and sometimes it will display the coef array, and other times it will crash before that. I'm 90% sure that the algorithms are correct, I'm just especially new to the OOP concepts so memory allocation/delocation is spotty for me. Thanks for the input so far.

//class
class Polynomial
{
private:
    double* coef;
    int degree;
    Polynomial(const Polynomial& base,double scalar,int mdegree);
    void reset(); // sets degree to zero, array one elem, and the coefficient to 0.0
    void checkandreduce(); // check if the degree has decreased after addition and reduce the polynomial

public:
    Polynomial(){coef=new double[1];degree=0;};
    Polynomial(const Polynomial& pol);
    ~Polynomial(){delete [] coef;}
    int getDegree(){cin>>degree; return degree;};
    bool check();
    void add(const Polynomial& p2);
    void multc(double factor);
    void subtract(const Polynomial& p2);
    void mult(const Polynomial& pol);
    void div(const Polynomial& divisor, Polynomial& quotient, Polynomial& remainder);
    Polynomial& operator=(const Polynomial& pol);

    friend Polynomial operator+(const Polynomial& p1, const Polynomial& p2);
    friend Polynomial operator-(const Polynomial& p1, const Polynomial& p2);
    friend Polynomial operator*(const Polynomial& p1, const Polynomial& p2);
    friend Polynomial operator/(const Polynomial& p1, const Polynomial& p2);
    friend Polynomial operator%(const Polynomial& p1, const Polynomial& p2);
    friend istream& operator>>(istream& stream, Polynomial& pol);
    friend ostream& operator<<(ostream& stream, const Polynomial& pol);

};

//copy constructor
Polynomial::Polynomial(const Polynomial& pol)
{
        degree=pol.degree;
        if(pol.coef)
        {
            coef=new double[degree+1];
            for(int i=degree;i>=0;i--)
                coef[i]=pol.coef[i];
        }
        else coef=0;
}

//overloaded operator=
Polynomial& Polynomial::operator=(const Polynomial& pol)
{
    if(this == …
gnarlyskim 1 Junior Poster in Training

Having issues with this program. I've been trying to identify all the areas where data is created, then tried to destroy it likewise after using it. I've put a lot of delete[] coef (coef is a pointer double array to hold coefficients). The program will run half the time, then crash half of the time. The algorithms are correct for what I need to do; however, I just can't wrap my head around the crash issue, nor identify the memory issue. Any help is greatly appreciated!

//multiply function used within the overloading, the multiplication takes one polynomial as constant, then breaks apart the second part one term at a time and uses a private constructor to shift the first polynomial by each term's degree and scale it by the coefficient of that term.
void Polynomial::mult(const Polynomial& pol)
{
    Polynomial r;
    r.degree=degree+pol.degree;
    delete[] r.coef;
    r.coef=new double[r.degree+1];
    for(int i=r.degree;i>=0;i--)
        r.coef[i]=0.0;
    Polynomial copy;
    delete[] copy.coef;
    copy=*this;

    for(int i=pol.degree;i>=0;i--)
    {
        Polynomial p1(copy,pol.coef[i],i);
        r.add(p1);
        p1.~Polynomial();
    }

    delete[] coef;
    *this=r;
    r.~Polynomial();
    copy.~Polynomial();
}

//overloaded operator to multiply two polynomial objects, while keeping the original objects the same (const).
//called as a friend function
Polynomial operator*(const Polynomial& p1, const Polynomial& p2)
{
    Polynomial pol1(p1);
    Polynomial pol2(p2);

    pol1.mult(pol2);
    return pol1;

    pol1.~Polynomial();
    pol2.~Polynomial();
}

//how it's called in main
cout<<"("<<p1<<")*("<<p2<<")="<<p1*p2<<endl;

//how it's outputted
ostream& operator<<(ostream& stream, const Polynomial& pol)
{
//outputting using "stream<<output"
    return stream;
}
gnarlyskim 1 Junior Poster in Training

>>Does this mean I have an error within the program,
Yes, your program is buggy. Coding and getting a clean compile is only about 25% the job of a programmer. The other 75% if fixing bugs.

>>or could there be an error in the compiling process?

Unlikely. Don't blame the compiler for your buggy program.

Thanks for the reply. I don't know much about the compiling process/different compilers. I just use the compiler I'm told to, and the coding is enough for me to handle. I figured it was an error, but wishful thinking made me ask this :-/.

gnarlyskim 1 Junior Poster in Training

I'm working (well have been for the past few weeks) on a polynomial class to do different things between two polynomials: multiply, divide, get remainder, subtract, add. The coefficients are stored in a pointer to an array listed under private and the degree (also the amount of slots in the array) is stored as private as well. During definition of many functions, a lot of instances of the class are created/destroyed/modified via dynamic allocation etc. I've come up with a solution for the required program, but when I compile it, the program crashes half of the time, and works the other half of the time. Does this mean I have an error within the program, or could there be an error in the compiling process? Just curious..Thanks for any insight.

(by the way, compiler is Code::Blocks 8.02 and OS is windows 7...let me know if there's anything else you need)

gnarlyskim 1 Junior Poster in Training

Ambiguity FTL ha. Ignore my suggestions about what is contained within the parenthesis of the for loop, just ensure that you cover all of the values within the array. I apologize for the misinformation.

If you want each corresponding day with the rainfall, my suggestion about dayNo+1 in the cout instead of incrementing MAX.

If you want the total max amount of days, disregard everything I've said and I apologize for the misleading information.

gnarlyskim 1 Junior Poster in Training

I want the program to test if there is more than 1 day that has the highest rainfall and susequently to output those corresponding days.

Each corresponding day with the max rainfall, or the corresponding amount of days that has the max rainfall?

gnarlyskim 1 Junior Poster in Training

Make sure you check usage and context before you make suggestions. As drew has written the program, MAX is the count of days that had rainfall equivalent to the highest rainfall total. It is NOT the maximum rainfall value in the series as you seem to have assumed. The variable "rainiestValue" is that number. Despite the naming and display issues, the usage and process are correct, drew just forgot to initialize MAX before doing anything with it.

As such, the use of "MAX = rain[0]" is incorrect and will lead to invalid results, especially when you consider that you would be truncating a double to an int and losing accuracy/data. MAX MUST be initialized to 0 so that the counter works correctly.

@OP
To correct the issue in question, all you need to do is add "= 0" to the declaration of MAX on line 7. I would advise you to change the name of the variable to something more descriptive such as "maxValueCount" while you are adding that.

In my version I initialized my value to rain[6], but I also created it as a double. I did not initialize his value to 0 and it still worked however.

drew (nice name. it's mine too):

-If you're going to do your first loop as you do, you'll want to include dayNo<= 7, so you don't miss the last day due to your pre-incrementation in the loop.

-I'd revise your second for loop. Currently, if you go …

Fbody commented: Ugh, no more warnings. Pay attention to the poster's algorithm. Yet again you have provided incorrect advice. +0
gnarlyskim 1 Junior Poster in Training

^^ check edited post for even more fun! haha

gnarlyskim 1 Junior Poster in Training
Term& Term::operator +=(const Term &t)

Added the reference. Not positive because I don't know what the class Term consists of, but I don't think you can use cin with an object of a class. I am not completely sure of this, so it's worth looking into. Just throwing some suggestions out there.

gnarlyskim 1 Junior Poster in Training

create a pointer to the array then use "object pointed to"=new "type"

ex:


double* array;

array=new double[69];

Or if you really want to get crazy, you can have the user input the size, but make sure to remember data is stored in the 0th spot of an array (array[0]):

double* array;
int size;

cout<<"Enter size of the array : ";
cin>>size;
array=new double[size];
josolanes commented: Great idea +1
gnarlyskim 1 Junior Poster in Training

Next project in my C++ course is to create a class Polynomial to add, subtract, multiply by a scalar, and multiply by another polynomial. I've written my code, and it works fine when I run it, but there's an application that is provided by our instructor to compare my .exe file with the solution.exe using an input file (.inp). I run the program myself and I see no errors, but when I compare it to the solution via this application, I get some odd answers like 68287e-313.

I've tried several input files and it seems that during the polynomial*polynomial section of the class is where the problems arise. This is my first experience with dynamic allocation, so I feel as though this may be the problem. I've tried peppering cout's throughout the code, and it gives me the correct numbers.

By no means have I written this the easiest or most conventional, but if anyone sees a possible problem with dynamic memory or anything else, I'd appreciate suggestions. I don't want to post the whole code as of yet, so I will post the information needed to look at my problem (compiled with Code::Blocks and windows 7):

//private constructor
Polynomial(const Polynomial& base,double scalar,int mdegree)
    {
        delete[] coef;
        degree=base.degree+mdegree;
        coef=new double[degree+1];
        for(int i=degree;i>=0;i--)
            coef[i]=0;

        for(int i=base.degree;i>=0;i--)
        {
            if(base.coef[i] != 0)
            coef[i+mdegree]=base.coef[i];
        }
        if(mdegree!=0)
        coef[0]=0;
        multc(scalar);
    };


//uses private constructor to separate the second polynomial (pol2), multiplies it by a constant via multc(), and shifts its degree (due to …
gnarlyskim 1 Junior Poster in Training

In going with that Fbody said above, initialize your MAX value to rain[0]. That will solve what he is saying and save you a line or two as well.

Set MAX equal to the first number in the array rain (MAX=rain[0]). Don't forget that arrays store information in the [0] slot as well. From there, you can start at 1, and go all the way to 7 and compare the current value in the array to your value for MAX, if it is larger, then you can set MAX=rain[whatever_integer_you_designate_in_the_for_loop].

The in your second for loop, you can start at rain[0], and if it equals MAX, then use something similar to what I posted above. (I initialized my int to be "i")

If I were you, I'd familiarize myself with for loops. They are an excellent tool to go through arrays.

Hint from above:

if(rain[i]==maxRain)
    cout << "\nThe highest rainfall is: " << maxRain << "mm" << " on day " << i+1;
gnarlyskim 1 Junior Poster in Training

I'll give an example of what I've been working on for my C++ class: consider a program to process polynomials (add, subtract, multiply etc).

I created a class called Polynomial. From within this class, I had private variables of an array to hold the coefficients of a polynomial, as well as the degree (aka x^2+x+1 is degree=2). I had member functions that would do the processes (add, subtract, multiply) that I defined just like a normal function, but including the private variables.

Within the main function, I could create different objects of the class, aka create different polynomials. They are declared just like a variable (well given how you establish your constructor, look that up) so like this
"Polynomial poly1;"
From there I can use any of the functions to compute what I want simply by calling them in context to a polynomial I created.
"poly1.add();"
or
"poly1.subtract();"

So in essence, classes are used to create different instances of objects that you want to use within your main function.

I hope this helps somewhat.

gnarlyskim 1 Junior Poster in Training

Make sure to enclose all C++ code within the code tags. http://www.daniweb.com/forums/announcement8-3.html

Look up ifsteam and ofstream. You'll need the <fstream> header as well. This is the method you might want to use for opening a file to read (ifstream) and outputting your data (ofstream).

One method of doing so is using strings. Input each line into a string, finding the space (" ") between words and creating substrings (.substr()) to hold each word, then find the next one.

So here are some things to look up:
-ifstream/ofstream
-string c++
-using strings to find a word in a sentence (google this and I would bet that someone has created a site/tutorial for almost exactly what you need to do)

Hope that helps.

gnarlyskim 1 Junior Poster in Training

What they said^^.
Here's one way, may not be the best:
Just looking at what you need to accomplish, you can use two "for" loops.

Set a double (say maxRain) equal to the first number in the array, then use the first for loop to cycle through and compare the current value in the array to maxRain, if the value in the array is greater than maxRain, set that value equal to maxRain.

At this point, your variable maxRain will equal to the highest value of rainfall.

Use your second loop to cycle through the array to see if any are equal to maxRain. I'll give you a hint, here's what I had in my for loop:

if(rain[i]==maxRain)
    cout << "\nThe highest rainfall is: " << maxRain << "mm" << " on day " << i+1;

Good Luck

gnarlyskim 1 Junior Poster in Training

Ohh ok I see. That should help me a lot! Thank you very much for your patience.

gnarlyskim 1 Junior Poster in Training

water and doe are two different objects that are supposed to hold different information. I want to create a third object, within doe's calling of function1 (within the definition of function1), that has the same attributes of doe.

gnarlyskim 1 Junior Poster in Training
void Example::function1( const Example& ex )
{
    Example copy_of_ex( ex ) ;

    /* whatever */

}

I want the copy to contain the attributes of the original object in which it is being called from the main.

int main()
{
    Example doe;
    Example water;
    
    doe.function1(water);
}

I want to make a copy that has the attributed of doe to use within function1.

gnarlyskim 1 Junior Poster in Training

I'm trying to clean up my coding a bit for a program I'm working on. Here's an example of my code (not my exact code, but I've adapted it to an example):

class Example
{
private:
    double* group;
    int number;
public:
    Example() {group=new double[1]; number=0;};
    Example(const Example& ex);
    Example& Example::operator=(const Example& ex);
    void function1(const Example& ex);
};

Example::Example(const Example& ex)
{
        number=ex.number;
        if(ex.group)
        {
            group=new double[number+1];
            for(int i=number;i>=0;i--)
                group[i]=ex.group[i];
        }
        else group=0;
}


Example& Example::operator=(const Example& ex)
{
    if(this == &ex)
        return *this;

    delete [] group;
    number=ex.number;

    if(group != ex.group)
    {
        group=new double[number+1];
        for(int i=number;i>=0;i--)
            group[i]=ex.group[i];
    }
    else group=0;
    return *this;
}

I want to be able to create a copy object of Example that is the same as the original. I've created a copy constructor and overloaded the assignment operator, but if I call the member function from within main, then in my definition of the member function function1, how can I create a copy for computational purposes? This is what I've been doing, but I feel like there's an easier way:

Example copy2;
        copy2.number=number;
        copy2.group=new double[number+1];
        for(int i=number;i>=0;i--)
            copy2.group[i]=group[i];

(Sorry if this is confusing, let me know and I'll try to explain a different way if need be)
Thanks!

gnarlyskim 1 Junior Poster in Training

Vectors aren't covered in this class so that's a no go, but thank you for the suggestion. I fiddled with my code and wrote several ways to accomplish what I needed (funny enough, the simplest version is the only one that actually works), but I'm encountering a weird crash. I believe it may be a problem with dynamically allocated memory, so I'll look into that for a day or two and if I can't figure it out then I'll come back crying...but for now, problem solved! Thank you.

gnarlyskim 1 Junior Poster in Training

Say I have an array:

array={1, 2, 3}

but I want to be able to increase the size, and shift the data to the front, leaving 0's behind. So i want the array to turn into this:

array={1, 2, 3, 0, 0}

Where I added two to the size of the array and shifted the data over. Can I change the size of the array without deleting the data within it?

gnarlyskim 1 Junior Poster in Training

It looks like a class declaration with private coef and degree then the member functions stated and declared and established within a main function. Message me in two weeks and I can show you then.

gnarlyskim 1 Junior Poster in Training

I'm currently using the "for" statement to input each coefficient. I just found a website that showed me how to dynamically allocate the array, so I can do that.

Overall however, the guidelines state "code cannot be reused from projects 3 and 4", which is what I have here. Having said this, my current project is the introductory OOP project, so they may be saying that I should include the input of the coef into a member function rather than in main. Just a thought if there's no other efficient way of accomplishing this input.

gnarlyskim 1 Junior Poster in Training

I'm looking for a few suggestions on different ways to input a polynomial into an array (coef[]) using a degree (double degree). I have one way that works, but my most recent project needs a new way to do the same thing (not sure why but it can't hurt to explore parts of the language that I don't know yet). Here's my current solution:

double coef[11];
int degree;

cout<<"Enter degree of the polynomial : ";
cin>>degree;
cout<<"Enter space separated coefficients starting from highest degree\n";
    for(int i=degree;i>=0;i--)
    cin>>coef[i];
gnarlyskim 1 Junior Poster in Training

Dave, thanks for the help. That actually helps a lot in what I need to do, since (in addition to what you said) I'll have to have an option to add another polynomial, so I'll have to set the previous back to void.

Banfa, thank you for your explanation as well. I will take that information and work on my project a bit more now that these parts are explained.

gnarlyskim 1 Junior Poster in Training

I'm working on a project for my first use of classes and OOP. I've read all our slides (only provided examples though) and two tutorials on classes, but I confused about a few things. I'll show first the assignment then I'll post my specific questions after.

You will need to implement a class called Polynomial10 and use it in the main function of
your solution. This class represent a set of all polynomial of a degree not higher than 10. Note,
that such a set is closed with respect to addition, subtraction and scaling by constant. Private
members coef and degree store the array of polynomial coe!cients and the degree. Public
methods are responsible for interaction between the objects of this class and the program.
Member functions print() and read() provide console output and input. Member
functions add() and subtract() update a polynomial object by performing an appropriate
arithmetic operation with another object. Member function multc() scales the polynomial by
a constant. You are welcome to update the code you created for previous projects.
This class has the following prototype:

class Polynomial10
{
private:
     double coef[MAX_DEGREE+1];
     int degree;
public:
     Polynomial10(); //Constructor for a new Polynomial10
     int getDegree(){return degree;};
     void print(); //Print the polynomial in standard form
     void read(); //Read a polynomial from the user
     void add(const Polynomial10& pol); //Add a polynomial
     void multc(double factor); //Multiply the poly by scalar
     void subtract(const Polynomial10& pol); //Subtract polynom
};

1. I'm confused …

gnarlyskim 1 Junior Poster in Training
gnarlyskim 1 Junior Poster in Training

how to write a program in c++ for this type of question?


Write a calculator program in c++ that allows the user to select which operation they would like to perform such as:
Addition,
subtraction,
multiplication,
division,
modulus,
Square,
Square root,
Convert Celsius to Fahrenheit (Fahrenheit = 1.8 Celsius +32),
Convert Celsius to Kelvin (add 273.15 °),
Convert Fahrenheit to Celsius (Celsius = (F-32) x (5/9)),
Convert Fahrenheit to Kelvin (Kelvin = 5/9 x (Fahrenheit - 32) + 273).

Make sure your program contains menu and will keep on looping until the user enter a specific value to end it. Please use Functions to do the calculation. You might want to use switch for the menu.

how to write this....?


question 2:


A parking garage charges a RM2.00 minimum fee to park for up to three hours. The garage charges an additional RM0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24 hour period is RM10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that will calculate and print the parking charges for each of 3 customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterday’s …

gnarlyskim 1 Junior Poster in Training

Ahh I see. I knew it was inputting something in place, but that explains it. Problem solved. Btw, I got lucky for this one and the deadline got pushed back till this Wednesday. All done now so one less thing to worry about. Thanks a lot.

gnarlyskim 1 Junior Poster in Training

WaltP- I did state

Why didn't you mention what it is inputting? (contents of all the variables being input). Follow that by what you expected it to input (expected contents of all the variab

and

And are you sure the coeff array is being loaded properly? output it after the loop.

in previous posts. But I do realize I can be a little sloppy with my questions, so I will work to state things in a way that people can help easier.

On topic: I've figured out my issue. I had been using the variable "n" in both the main function and process functions. This was confusing the input. I changed "n" to "p" in process, and it works perfectly. I realized this through jonsca's idea to play with the function in a different main function.

Final Issue (see code below): When selecting option 4, it automatically reads in the '4' character as the

cin.getline(fname, sizeof(fname));
              in.open(fname);

section. What I can't figure out is how to offset the '4' character so that the program doesn't immediately read in '4' and view it as an input for the file name. Any suggestions?

int main (void) {
    char userChoice;
    ifstream in;
    ofstream out;
    int n,x,i,degree,j;
    bool done=false;
    char fname[40];
    char fname2[40];
    double a,b;
    double coef[10];
    cout << "\nCGS 2421 Integrals of polynomials\nThis program finds definite integral\nof polynomial on [a,b]\n\n";
    cout << "0. Quit\n1. Enter polynomial\n2. Print polynomial\n3. Integrate\n4. Process batch\n\nEnter your choice : ";
    userChoice = firstChoice();
 do{ …
gnarlyskim 1 Junior Poster in Training

And with this information, what can we say? Doesn't anyone that needs help understand the concept of details?

If you know it's not inputting properly, why didn't you mention that? Why didn't you mention what it is inputting? (contents of all the variables being input). Follow that by what you expected it to input (expected contents of all the variables)

Details are the only thing that helps, not vague descriptions. Save yourself another 4 hours of pain and loss of sleep.

I apologize for this. I've honestly been trying to explain where I'm at and what I'm having trouble with and providing my code for what I've done.

From your post, I'll update my issue to clarify.

I know it is inputting. I think that somewhere the value after the degree is missing (look at the example I supplied two posts up) and from there, the coefficients are being inputted improperly. I believe the area of concern is the for(int i=n+1;i>=0;i--) loop after the in>>n.

gnarlyskim 1 Junior Poster in Training

Did you try outputting each and every value read from the file to see if something is wrong in your loop? And are you sure the coeff array is being loaded properly? output it after the loop.

The loop looks suspicious to me.

What do you mean by suspicious?

Sorry bear with me. I've been staring at this code for near 20 hours this week in addition to a combined 60 hours of calc 3, statics, and chem 2. It all is blending together...

I know it's not inputting the value correctly, but I'm failing to understand the mistake that it's making. It looks right to me, but I know it's not. I tried doing a cout<<coef[n] after the in>>a>>b, and that output 331, which should be 111

gnarlyskim 1 Junior Poster in Training

Also, Here's my process method

int process(ifstream& in, ofstream& out)
{

    int n;
    double a,b,coef[11],average;
    double sum1=0;
    double sum2=0;
    double hold1,hold2,finalSum;

while(in>>n)
    {
    in>>n;
    for(int i=n+1;i>=0;i--)
        in>>coef[i];
    in>>a>>b;



    out<<"Average of ";
    if(coef[n]==1) out << "x^" <<n;
    if(coef[n]==-1) out << "-x^" <<n;
    if(coef[n]>0 && coef[n]!=1) out << coef[n]<<"*x^"<<n;
    if(coef[n]<0 && coef[n]!=-1) out << coef[n]<<"*x^"<<n;

    for(int i=n-1;i>=2;i--)
    {
        if(coef[i]>0) out<<"+";
        if(coef[i]==1) out<<"x^"<<i;
        if(coef[i]==-1) out<<"-x^"<<i;
        if(coef[i]<0 && coef[i]!=-1) out<<coef[i]<<"*x^"<<i;
        if(coef[i]>0 && coef[i] !=1) out<<coef[i]<<"*x^"<<i;
    }
    if(coef[1]==1) out <<"+x";
    if(coef[1]==-1) out<<"-x";
    if(coef[1]>0 && coef[1] !=1) out<<"+"<<coef[1]<<"*x";
    if(coef[1]<0 && coef[1] !=-1) out<<coef[1]<<"*x";

    if(coef[0]>0) out<<"+"<<coef[0];
    if(coef[0]<0) out<<coef[0];

    out<<", on ["<<a<<","<<b<<"] is ";

    for(int i=n;i>0;i--)
     {
         hold1=sum1;
         sum1=coef[i]*(pow(a,i+1)/(i+1));
         sum1=sum1+hold1;
     }
     sum1=sum1+coef[0]*a;

     for(int i=n;i>0;i--)
     {
         hold2=sum2;
         sum2=coef[i]*(pow(b,i+1)/(i+1));
         sum2=sum2+hold2;
     }
     sum2=sum2+coef[0]*b;
     finalSum=sum2-sum1;
     average=finalSum/(b-a);
     out<<average;

     for(int i=n;i>=0;i--)
     coef[i]=0;
     n=0;
     a=0;
     b=0;
     out<<endl;
    }
}

And here's what I have in main()

case '4': do { // until open is successful
              cout << "Enter input file name : ";
              cin.getline(fname, sizeof(fname));
              in.open(fname);

            if (in.fail()) {
            cout<<"Open error!\nTry again.\n"<<endl;
            in.clear();
            }
            else done = true;
            } while (!done);
            done=false;
            do {	         // until open is successful
                cout << "Enter output file name : ";
            cin.getline(fname2, sizeof(fname2));
            out.open(fname2);

            if (out.fail()) {
            cout<<"Open error!\nTry again.\n"<<endl;
            out.clear();
            }
            else done = true;
            } while (!done);

            process(in,out);

            cout<<endl;
            break;
gnarlyskim 1 Junior Poster in Training

I've found a way to open the input and output files within the main() function. I put the process(in,out) in a separate file like you did and did not get the same error, but when I went back to my original code, I got the error again. It says :

Enter input file name : Open error!
Try again.

Ente rinput file name : (it works from here)

I am having problem with the input of the coefficients. I tried a simple input file of this :

3 1 2 3 4 1 1
2 1 2 3 1 1
1 1 2 1 1

and got the output of this:

Average of 3*x^1+3*x+4, on [1,1] is NaN
Average of 3*x^1+3*x+1, on [1,1] is NaN
Average of x^2, on [0,0] is NaN

Here is what it should look like :

Average of x^3 + 2*x^2 + 3*x + 4, on [1,1] is ....
Average of x^2 + 2x + 3, on [1,1] is ...
Average of x + 2, on [1,1] is ...

where ... is solved for average integral (I can do this part)

Ideally I want to be able to finish this tonight so I appreciate any help anyone can give me! I'll be working on it until 11:59 (after this I automatically lose 20% :() Thanks!

gnarlyskim 1 Junior Poster in Training

Also, I had wanted to say it's really cool that you decided to join the site as a sponsor. I'm confident that it means a lot to Dani too. :)

I was raised and still believe that when someone helps you, you should thank them. I appreciate this community and it's ability to help others for a common goal so a little donation is worth more than it costs.

I'm about to head off for another job trip in a few minutes so I don't have time to play around with the code right now, but the first due date is tonight at 11:59 so you know I'll be on later. I'll reply back with any more updates/issues.

gnarlyskim 1 Junior Poster in Training

I was able to solve my crash issue, (I think the opening of in/out works now), but I can't get any output in my output.txt file that I use.
Also, I wanted to avoid pointers if at all possible since we're just learning them this week, so I tried taking note of the n+1 factors and implementing it. I must not be inputting or outputting correctly. Here is my updated method with changes (note I found that we should use process as an int) :

int process(ifstream& in, ofstream& out)
{

    int n;
    double a,b,coef[11],average;
    double sum1=0;
    double sum2=0;
    double hold1,hold2,finalSum;
    bool done=false;
    char fname[40];
    char fname2[40];

  do { // until open is successful
      cout << "Enter input file name : ";
      cin.getline(fname, sizeof(fname));
      in.open(fname);

    if (in.fail()) {
      cout<<"Open error!\nTry again.\n"<<endl;
      in.clear();
    }
    else done = true;
  } while (!done);
    done=false;
  do {	         // until open is successful
    cout << "Enter output file name : ";
    cin.getline(fname2, sizeof(fname2));
    out.open(fname2);

    if (out.fail()) {
      cout<<"Open error!\nTry again.\n"<<endl;
      out.clear();
    }
    else done = true;
    } while (!done);


while(in>>n)
    {
    in>>n;
    for(int i=n+1;i>=0;i--)
        in>>coef[i];
    in>>a>>b;
    n=n+1;



    out<<"Average of ";
    if(coef[n]==1) out << "x^" <<n;
    if(coef[n]==-1) out << "-x^" <<n;
    if(coef[n]>0 && coef[n]!=1) out << coef[n]<<"*x^"<<n;
    if(coef[n]<0 && coef[n]!=-1) out << coef[n]<<"*x^"<<n;

    for(int i=n-1;i>=2;i--)
    {
        if(coef[i]>0) out<<"+";
        if(coef[i]==1) out<<"x^"<<i;
        if(coef[i]==-1) out<<"-x^"<<i;
        if(coef[i]<0 && coef[i]!=-1) out<<coef[i]<<"*x^"<<i;
        if(coef[i]>0 && coef[i] !=1) out<<coef[i]<<"*x^"<<i;
    }
    if(coef[1]==1) out <<"+x";
    if(coef[1]==-1) out<<"-x";
    if(coef[1]>0 && coef[1] !=1) out<<"+"<<coef[1]<<"*x";
    if(coef[1]<0 && coef[1] !=-1) out<<coef[1]<<"*x";

    if(coef[0]>0) out<<"+"<<coef[0];
    if(coef[0]<0) out<<coef[0];

    out<<", on ["<<a<<","<<b<<"] …
gnarlyskim 1 Junior Poster in Training

I appreciate the help and explanations. .eof was emphasized pretty widely in the class, so I figured it made sense here, but that link you posted couldn't be more applicable.

I tried compiling and it went through, but every time i run it and try option 4, it crashes. Is double the right declaration for process(ifstream& in, ofstream& out) ?? Not sure how to prototype this, but I feel like the body of this prototype accomplishes what I want to do.

gnarlyskim 1 Junior Poster in Training

I've been looking at this (and numbers) too much recent, everything seems the same...I've done a little revamp on the whole opening scenario from a little help from the lecture slides (who would have thought).

Main areas of thought :
1) implementation of prototype double process(in,out)---is this correct?
2)the prototype double process(instream& in, ofstream& out) as a whole, however mainly on the ability to accept a file name

#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<fstream>
using namespace std;

char getChoice();
char firstChoice();
int getN();
double f(double x, double coef[], int n);
double integral(double a, double b, double coef[], int n);
void print_polynomial(double coef[], int n);
double process(ifstream& in, ofstream& out);



int main (void) {
    char userChoice;
    ifstream in;
    ofstream out; //is this needed?
    int n,x,i,degree;
    double a,b;
    double coef[10];
    cout << "\nCGS 2421 Integrals of polynomials\nThis program finds definite integral\nof polynomial on [a,b]\n\n";
    cout << "0. Quit\n1. Enter polynomial\n2. Print polynomial\n3. Integrate\n4. Process batch\n\nEnter your choice : ";
    userChoice = firstChoice();
 do{
    switch(userChoice)
    {
    case '0': //ends program
            return 0;

    case '1': cout << "Enter degree of a polynom between 2 and 10 : ";
            n=getN();
            cout << "Enter space separated coefficients starting from highest degree\n";
            for(i=n;i>=0;i--)
                  cin>>coef[i];
            break;

    case '2':  print_polynomial(coef,n);
            cout<<endl;
            break;

    case '3': integral(a, b, coef, n);
            cout<<endl;
            break;

    case '4': process(in,out);

            //This case is the area in which the input file would be read,
             //processed, and outputted.

            cout<<endl;
            break;
    }
    cout << "0. Quit\n1. Enter polynomial\n2. Print polynomial\n3. Integrate\n4. Process batch\n\nEnter your choice : …
gnarlyskim 1 Junior Poster in Training

Hmm yes valid point, however I think the others prior to me reinforced the idea that acting like a jerk isn't a good idea.

That is one example of a way to solve an exponent. Who is to say that this is what he or she needed exactly. Chances are extremely slim.

I'm a student in my first C++ class and I've learned primarily through trial and error and help from other people from forums. My first few codes were mostly written by other people, but I had to adapt and learn the language (or little of what I know) because of the fact that no one is going to sit down and write a long code because you don't want to. If anything, this code helped me as a practice, so I don't mind supplying it to him. If he takes this little code and researches and plays around with it, then I've succeeded.


Now all this being said, Robby14, attempt to phrase your question in a manner than won't anger people...

Edit: Not even going to bother. Suffice to say, Gnarlyskim - you're just reinforcing negative behaviour.

he did say "please" in his topic title ;) haha.

But at least he posted SOMETHING for code. There has been worse, even on the limited time I've been on this site.

gnarlyskim 1 Junior Poster in Training

These are the posts that scare me about asking for coding help...haha.

#include<iostream>
#include<cmath>
using namespace std;

int main()
{

double a,b,answer;

cin>>a>>b;

answer=pow(a,b);

cout<< answer;

return 0;

}
gnarlyskim 1 Junior Poster in Training

These are the posts that scare me about asking for coding help...haha.

gnarlyskim 1 Junior Poster in Training

Having a little trouble with configuring the code so that the user can input the name of the text input and output files. Here's what I have now as far as cout/cin for the input files and the declarations :

char input;
    char output;

    cout<<"Enter input file name : ";
    cin >> input;
    cout<<"Enter output file name : ";
    cin >> output;
    while(!in.eof())
    {
    in.open(input);
    while(false)
    {
        if(in.fail())
        {
            cout<<"input file did not open please check it\n";
            return false;
        }
    }
    out.open(output);
gnarlyskim 1 Junior Poster in Training

I really appreciate the help jonsca. This site really helps relieve some stress :sweat: so I've decided to donate a years worth. I feel that it has a lot to offer me and well worth the money. Just wanted to let you know that your help motivated my actions. But on topic:

I spent a few minutes today and tried to do what you had suggested. I created this within a prototype function to do what I need to for easy implementing within the main function. I'm about to head to work but I wanted to see if I'm going along the right path/a little proof reading.

What I haven't done :
1) Find a way to delete array for each separate line of data
2)Close files
3)More things that I can't think of now( haha)

process(ifstream& in, ofstream& out)
{
    ifstream in;
    ofstream out;
    int n;
    double a,b,coef[],average;
    double sum1=0;
    double sum2=0;
    double finalSum;
    double hold1,hold2;

    cout<<"Enter input file name : ";
    cin>>input;
    cout<<"enter output file name : ";
    cin>>output;

    in.open(input);
    while(false)
    {
        if(in.fail())
        {
            cout<<"input file did not open please check it\n";
            return false;
        }
    }
out.open(output);

    in>>n;
    for(i=n+1;i>=0;i--)
        cin>>coef[i];
    in>>a>>b;



    out<<"Average of ";
    if(coef[n]==1) out << "x^"<<n;
    if(coef[n]==-1) out<< "-x^"<<n;
    if(coef[n]>0 && coef[n]!=1) out << coef[n]<<"*x^"<<n;
    if(coef[n]<0 && coef[n]!=-1) out << coef[n]<<"*x^"<<n;

    for(int i=n-1;i>=2;i--)
    {
        if(coef[i]>0) out<<"+";
        if(coef[i]==1) out<<"x^"<<i;
        if(coef[i]==-1) out<<"-x^"<<i;
        if(coef[i]<0 && coef[i]!=-1) out<<coef[i]<<"*x^"<<i;
        if(coef[i]>0 && coef[i] !=1) out<<coef[i]<<"*x^"<<i;
    }
    if(coef[1]==1) out <<"+x";
    if(coef[1]==-1) out<<"-x";
    if(coef[1]>0 && oef[1] !=1) cout<<"+"<<coef[1]<<"*x"; …
gnarlyskim 1 Junior Poster in Training

Thanks, jonsca. That makes a lot of sense. I'm going to the library this evening to try to get all my work done so I'll work on implementing it. Doesn't seem too difficult, but I probably shouldn't speak too soon. I'll reply back here if there's any more questions. Thanks again

gnarlyskim 1 Junior Poster in Training

Pending that I can use the >> operator to assign a single line to an array of coef[]...

If I input each line separately as an array, say coef[12] (since 12 would be the max amount of values that we are required to have), how would I find the very first value of that array (coef[max]) since the array can be any value between coef[4] and coef[12]?

Also, how do I separate each line of data, say I had three lines but I wanted to input only one line to process it completely, then move to the next?

gnarlyskim 1 Junior Poster in Training

I have to be able to read text from a file then manipulate it to find the average value of an integral over a given bounds [a,b] from an input file, then export it to another file. I do not know how to store the information to process it. Say this is the input file input.txt (each line is a different polynomial):

3 1.3 0.9 4.7 2 -5.4 5
2 5 6.3 1 0.4 10.7
1 1 0 -1 2

I would want to be able to store the bold numbers as the degree of the polynomial. The underlined numbers are the values of a,b respectively. the rest of the numbers are the coefficients.

ex) line 1 would be 3rd degree polynomial 1.3x^2+0.9x+2 integrated over [-5.4,5]

I realize if I store each line as an array of coef[], I can set
a=coef[1]
b=coef[0]
but I don't know how I would find the degree (bold number, first number in each line) to set it equal so that I can evaluate the polynomial to integrate etc. since the lines each have different amounts of numbers. If i can get these each set to a separate memory, then I know how to evaluate the integral and print like I need it.

Here's my code so you may see what I am doing (pardon the redundancy). Please let me know if I am unclear:

#include<iostream>
#include<cmath>
#include<cctype>
using namespace std;

char getChoice();
char firstChoice();
int …
gnarlyskim 1 Junior Poster in Training

change to a sports major and forget about programming.
It's obviously totally uninteresting (at least if you think you have your priorities right in going to a sports thingie instead of going to school).

It's my job...I get my school paid for by doing this so I don't have much of a choice.

Also, thank you thomas_naveen, great link.

gnarlyskim 1 Junior Poster in Training

So I've missed the past week of my C++ class due to the SEC swimming championships being a week long :@, and I've missed the whole topic on file processing. I've been reading the slides and a few tutorials via lovely google searching, but it's a little hazy. Can anyone pleasee point me in the direction of where to go (some hints etc) or a tutorial that will fit to help me in what I need to accomplish this next project:
(A little background, I wrote a code for last weeks project that will accept the degree of a polynomial and the coefficients as coef[], and from there the program can print the polynomial or integrate it over a given interval)

Batch Polynomial Handling
By selecting option 4 on the main menu, the user will be able to specify the names of an input file
and an output file. The program will then read coefficient-boundary pairs from the input file and,
for each pair, print both the formatted polynomial and the average of that polynomial over the
interval specified. For example, consider the following input file:
1. 3 1.3 0.9 4.7 2 -5.4 5
2. 2 5 6.3 1 0.4 10.7
3. 1 1 0 -1 2
[Bold and underlines are added for clarification and are not in the input file.]
Each line of the input file describes one polynomial-boundary pair. The first integer (in bold here)
states …