2017-06-18 83 views
-1

我有一個任務,用一個公共方法創建一個C++ Tokenizer類 vector * GetTokens(void);執行過程中的C++類成員函數錯誤/異常處理

該函數在via stdin中使用一個字符串,對字符串進行標記,並返回size()= 1或2標記的向量指針。該函數在以下情況下需要拋出錯誤:有0個標記,超過2個標記,第一個標記不是字符串,或者第一個標記不是字符串,第二個標記不是整數。

Code that calls my function from professor: 
////////////////////// 
For (int i=0; i <5; i++) { 
    Tokenizer tok; 
    Vector<string> *test = tok.GetTokens(); 

    If (test->size()==1) { 
    cout << "Yay" << endl; 
    } else { 
    cout << "Boo" << endl; 
    } 
/////////////// 

我已經能夠成功地完成此程序的正確標記。我也通過if ... then語句打印出錯誤。但是,在我的錯誤期間,「Yay」或「Boo」仍然會打印出來。我需要而不是讓這個文本打印出來,同時仍然允許for循環/調用函數繼續執行。

有沒有辦法,在我的GetTokens()方法中使用斷言的異常或錯誤來實質上停止執行,打印我的錯誤文本,將控制權傳遞迴調用函數,而不打印出任何其他文本並進入下一個進度循環週期? ::::編輯::::

My Tokenizer.cpp 
/////////////////// 


'//Constructor 
Tokenizer::Tokenizer(void) { } 

//This includes my tokenization with my error/exception handling 
vector<string> * Tokenizer::GetTokens() { 
string strIN; 
cout << "> "; 
getline(cin, strIN); 

vector<string> *tokens = atokenizer(strIN); 

//So with one of my constraints, I need to print an error for 0 tokens 
try{ 
    if(tokens->size()!=0) { 
     return tokens; 
    } else { 
     throw tokens; 
    } 
} 
catch(vector<string> *error) { 
    cout << "ERROR!" << endl; 
    return error; 
} 
} 

//This is my tokenization function which parses by whitespace 
vector<string> *Tokenizer::atokenizer(string strIN) { 
vector<string> *tokens = new vector<string>(); 

string token=""; 
int c=0; 
bool whiteSpace=true; 

//Iterates thru all chars and tokenizes by " " 
for(int i=0; i<strIN.size(); i++) { 
    //Checks if char==1-0,a-z,etc. or is space=" " 
    if((strIN[i]>=33) && (strIN[i]<=126)) { 
     //If char, appends to token 
     token+=strIN[i]; 
     whiteSpace=false; 
    } 
    else if((strIN[i]==32) && (whiteSpace==false)) { 
     //If space, adds token to tokens 
     tokens->push_back(token); 
     token=""; 
     c++; 
     whiteSpace=true; 
    } 
} 

//Adds final token 
if(token!="") { 
    tokens->push_back(token); 
} 

return tokens; 
}' 
////////////////// 
+0

這是異常發揮作用的地方,閱讀它們並測試在'GetTokens'中拋出某些東西時會發生什麼。順便說一句,如果你的'GetTokens'不是絕對巨大的,那麼在這裏粘貼它可能會幫助 –

+0

歡迎來到Stack Overflow。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

投擲東西並立即捕捉到相同的功能沒有多大意義。通常你拋出你的函數上下文,讓一些調用函數來處理它。 – aschepler

回答

0

所以我想用不同的方式來解決我的問題。我無法得到任何錯誤處理或例外的工作。相反,我只是回到使用If ... then ... else語句與cout進行錯誤檢查,然後創建了控制打印輸出的函數。

void coutOff() { 
    cout.setstate(std::ios_base::failbit) 
} 

void coutOn() { 
    cout.clear(); 
}