我有一本书类,可以为书籍对象提供标题,作者,版权,ISBN号和结帐。但是,程序运行时出现运行时错误。在用户输入标题并按Enter后,程序将跳过,显示其余输出,然后终止程序,从而产生运行时错误。
我试图捕捉异常,但我没有得到任何东西。
代码:
#include "std_lib_facilities.h"
class Book{
public:
string what_title();
string what_author();
int what_copyright();
void store_ISBN();
void is_checkout();
private:
char check;
int ISBNfirst, ISBNsecond, ISBNthird;
char ISBNlast;
string title;
string author;
int copyright;
};
string Book::what_title()
{
cout << "Title: ";
cin >> title;
cout << endl;
return title;
}
string Book::what_author()
{
cout << "Author: ";
cin >> author;
cout << endl;
return author;
}
int Book::what_copyright()
{
cout << "Copyright Year: ";
cin >> copyright;
cout << endl;
return copyright;
}
void Book::store_ISBN()
{
bool test = false;
cout << "Enter ISBN number separated by spaces: ";
while(!test){
cin >> ISBNfirst >> ISBNsecond >> ISBNthird >> ISBNlast;
if((ISBNfirst || ISBNsecond || ISBNthird)<0 || (ISBNfirst || ISBNsecond || ISBNthird)>9)
error("Invalid entry.");
else if(!isdigit(ISBNlast) || !isalpha(ISBNlast))
error("Invalid entry.");
else test = true;}
}
void Book::is_checkout()
{
bool test = false;
cout << "Checked out?(Y or N): ";
while(!test){
cin >> check;
if(check = 'Y') test = true;
else if(check = 'N') test = true;
else error("Invalid value.");}
}
int main()
{
Book one;
one.what_title();
one.what_author();
one.what_copyright();
one.store_ISBN();
one.is_checkout();
keep_window_open();
}
不确定问题是什么。任何帮助表示赞赏,谢谢。
输出示例:
标题:一只飞过杜鹃鸟巢 (下一行实际上并没有间隔,所有输出都是一次) 作者:
版权年份:
输入以空格分隔的ISBN号:
此应用程序已请求Runtime以不寻常的方式终止它。请联系支持部门获取更多信息。
另外不要担心keep_window_open和错误函数。它们是std_lib_facilities.h的一部分,很可能不会导致问题。如果遇到问题,错误只会输出错误消息。
答案 0 :(得分:2)
这里的问题是C ++输入流不会删除它们遇到的格式错误的输入。换句话说,如果您尝试读取数字并且流包含例如字符“x”(不是数字),则不会从输入流中删除该字符。另外,如果我没记错的话,这也会使输入流处于错误状态,导致格式良好的输入也会失败。虽然有一种机制可以测试输入流的状态并删除错误输入并清除错误标记,但我个人发现总是读入字符串更简单(使用“&gt;&gt;”或“getline”)然后解析字符串。例如,对于数字,您可以使用“strtol”或“strtoul”函数。