This is a textbook example for the use functions. My compiler says there is a "syntax error before } token". I have been looking and testing for hours but don't find it. Can you help?
#include <iostream.h>
double mySquare(int aX)
{
return(aX * aX);
}
main()
{
int endNumber;
char ch;
do
{
cout << "Insert the number of squares desired ";
cin >> endNumber;
cout << endl;
for (int i = 1; i < endNumber + 1; i++)
cout << mySquare(i) << endl;
cout << endl << "Do you want to continue (y/n)?";
cin >> ch;
while (ch == 'y' || ch == 'Y');
}
}
This is horrible code. The problem you're looking for is that the function should end with
1 2
}while(...);
}
rather than
1 2 3
while(...);
}
}
Control structures are never inside their own {}s.
Now, all the other problems:
iostream header does not have a .h
cin, endl and cout are in std namespace so either prepend std:: to them or add usingnamespace std;
main() is a function and like any other function it needs a return type. The standard says int main(). I think it is allowed to omit the type in C or maybe only old C. Anyway, this is not valid in C++.
Thanks for all the quick answers. It works now!!! Concerning the book, it's "A first course in Computational Physics and object oriented programming in C++" from D. Yewick. And indeed it was a misprint in the book with the wrong bracket.
@ hamsterman
I am just starting but I assume that code for beginners always looks awful? Perhaps it will get better, or maybe I am using the wrong book. Was looking for something with physics applications and introduction into C++...
And if I am leaving the .h out my compiler doesn't understand the cin, cout commands any more. I am using Dev-C++ 4.9.9.0 (was on the CD which came with the book).
Had a quick look at the book on Amazon, It's not as old as the code suggests that it is. It looks like it is bundled with a CD with a compiler, I'm guessing that you are using this. This book may well teach you some bad habits and out of date style.
Dev-C++ 4.9.9.0 is not good, you could look at replacing it with something like Code::Blocks [http://www.codeblocks.org/ ] but you will have to work harder to convert the code from the book to a modern standard, have a look at the site C++ Language Tutorial for this: http://www.cplusplus.com/doc/tutorial/
Or alternatively learn C++ from a different source and that go back to that book to learn about using it in the physics domain.
Thanks for the information. I will have a look at the tutorial and already had a look at the Code::Blocks Compiler. It looks very sophisticated and demanding and probably only works for specialists. For my current humble needs Dev-C++ should suffice I think.