2009-07-17 54 views
0

我有一本書課,需要書名,書名,作者,版權,ISBN號和結賬。但是,我在程序運行時遇到運行時錯誤。在用戶輸入標題並按回車後,程序跳下來,顯示其餘的輸出,然後終止程序,給出運行時錯誤。運行時錯誤,可能的輸入問題?

我試圖捕捉一個異常,但我沒有得到任何東西。

代碼:

#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編號:

此應用程序請求運行系統以不尋常的方式終止它。請聯繫支持以獲取更多信息。

另外不要擔心keep_window_open和錯誤函數。它們是std_lib_facilities.h的一部分,很可能不會導致問題。錯誤只是在遇到問題時輸出錯誤消息。

+1

keep_window_open是什麼? – 2009-07-17 04:16:44

+0

如何顯示所有必要的代碼(如Alex建議的,keep_window_open),並顯示程序的輸入/輸出,以便我們可以準確瞭解打印的內容以及失敗的位置。 – Tom 2009-07-17 04:20:11

回答

2

這裏的問題是,C++輸入流不會刪除它們遇到的格式錯誤的輸入。換句話說,如果您嘗試讀取數字並且流包含(例如字符「x」(不是數字)),則該字符不會從輸入流中移除。此外,如果我沒有記錯,那也會使輸入流處於錯誤狀態,導致格式良好的輸入也會失敗。雖然有一種機制可以測試輸入流的狀態並去除格式錯誤的輸入並清除錯誤標誌,但我個人發現,總是讀取一個字符串(使用「>>」或「getline」),然後解析字符串。例如,對於數字,您可以使用「strtol」或「strtoul」功能。