I am trying to work my way through a c++ textbook to learn some programming, but I've run into an issue with some of the sample code. The goal is to write a simple calculator program, and the text supplies parts of the code as examples. A portion is:
if (!cin) error("no second operand");
The text makes it seem like 'error' will the output the text that comes after it if your input is incorrect, but my compiler just says 'error' hasn't been defined. I'm 开发者_开发问答copying the code from the text word for word, so I'm not sure if I'm missing something with my compiler, or if I've misunderstood how I should be writing the code. Can anyone give some advice?
You must have missed the definition of error()
function - it must be somewhere in the book, as it is not C++'s feature.
I assume the book is Stroustrup's Programming Principles and Practices? Check out the pages 149 and 150, it's explained there.
Put this code in a header file and include it in the example program:
#include <stdexcept>
void error(string s)
{
throw runtime_error(s);
}
void error(string s1, string s2)
{
throw runtime_error(s1+s2);
}
Maybe they (the authors) didn't mean for you to try to compile that code, but just to understand the example and maybe implement it yourself.
精彩评论