Output to the screen with a struct


MPD78
02-11-2009, 03:24 PM
I have a simple problem, I am unable to view the results from a struct statement that I defined in a header file. If I leave out the usual cout << statement the program compiles correctly but as soon as I include the cout << statement the compile generates errors. I have the proper #include statements and the using namespace std statement. Can someone shed some light on this problem?

Thanks
Matt

davekw7x
02-11-2009, 06:17 PM
... shed some light ...
Could we see your code? (Don't just tell us; show us.)

Regards,

Dave

MPD78
02-11-2009, 06:47 PM
Thanks for the quick response.

I moved all of the code to the .cpp file. This is the example given in chapter 1 of NR3.

davekw7x
02-12-2009, 10:18 AM
... example given in chapter 1 of NR3.

Well, in order to print the value that the functor gives, you have to use it as a function

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

using namespace std;

//
// A struct with a functor
// The functor calculates c*pow(x, p), where
// c and p are parameters fixed by the constructor
// and x is an input parameter for the evaluation.
//
struct Contimespow {

/// the struct definition goes here, including the functor implementation

};

int main()
{
//
// Create an object with c = 4.0 and p = 0.5
//
Contimespow h(4.0, 0.5);


//
// Here's a loop that uses the overloaded () operator
//
double x;

cout << "Enter a value for x: ";
cout << scientific;
while (cin >> x) {
cout << "h(" << x << ") = " << h(x) << endl << endl;
cout << "Enter another value for x: ";
}
cout << "Goodbye for now." << endl;

return 0;
}


Output from a typical run:


Enter a value for x: 1
h(1.000000e+00) = 4.000000e+00

Enter another value for x: 2
h(2.000000e+00) = 5.656854e+00

Enter another value for x: 3
h(3.000000e+00) = 6.928203e+00

Enter another value for x: 4
h(4.000000e+00) = 8.000000e+00

Enter another value for x: 5
h(5.000000e+00) = 8.944272e+00

Enter another value for x: 6
h(6.000000e+00) = 9.797959e+00

Enter another value for x: 7
h(7.000000e+00) = 1.058301e+01

Enter another value for x: 3.1415926535897932384626433832795029
h(3.141593e+00) = 7.089815e+00

Enter another value for x: Tttthat's all, Folks!
Goodbye for now.


Regards,

Dave

MPD78
02-12-2009, 04:24 PM
Dave,

Thank you very much. My code works just as it should and the struct statement makes perfect sense to me now.

Matt