2013-02-15 159 views
0

這裏是我的一小段代碼:cin是在這種情況下使用的正確功能嗎?

int read_prompt() { 
string prompt,fname,lname,input; 
int id; 
cout << "customers> "; 

cin >> prompt; 

if (prompt.compare("add") == 0) { 
    cin >> id; 
    cin >> fname; 
    cin >> lname; 
    NewCustomer(id,fname,lname); 
} else if (prompt.compare("print")==0) { 
    print_array(); 
} else if (prompt.compare("remove")==0) { 
    cin >> id; 
    RemoveCustomer(id); 
} else if (prompt.compare("quit")==0) { 
    return 0; 
} else { 
    cout << "Error!" << endl; 
} 
read_prompt(); 
return 0; 

} 

這只是正常,只要用戶沒有輸入任何意外。其中一個測試案例應該通過輸入「添加125英里/小時Daffy Duck」,其中id最終爲125,fname等於mph,並且lname等於Daffy。在這個函數接收到所有三個變量後,它會再次調用它自己並重新提示用戶,然後Duck進入哪個「錯誤!」明顯得到輸出。

如何在用戶輸入時捕獲此錯誤?在這方面,cin是最好的功能嗎?我查了getline(),但我有點不確定如何實現它。

+0

爲什麼不創建一個菜單驅動程序,允許用戶通過輸入接單數用'之開關來選擇所需要的功能。您將避免許多錯誤和驗證碼。 – ChiefTwoPencils 2013-02-15 20:06:37

+1

'cin'不是一個函數;這是一個對象。因此,它具有成員函數,並且有可以使用它的自由函數。其中許多是提取器,也就是'operator >>'的重載。 – 2013-02-15 20:10:11

回答

1

如果是我的話,

  • 我會讀整條生產線的同時,並把它分解成使用std::istringstream空格分隔的標記。
  • 我會不惜一切代價避免這種情況。
  • 我可能會添加更嚴格的錯誤檢查。

像這樣:

#include <vector> 
#include <boost/lexical_cast.hpp> 
#include <iostream> 
#include <sstream> 
#include <stdexcept> 

typedef std::vector<std::string> Args; 

std::istream& operator>>(std::istream& is, Args& args) { 
    std::string s; 
    if(std::getline(is, s)) { 
     std::istringstream iss(s); 
     args.clear(); 
     while(iss >> s) 
      args.push_back(s); 
    } 
    return is; 
} 

void NewCustomer(int, std::string, std::string) { 
    std::cout << __func__ << "\n"; 
} 
void RemoveCustomer(int) { 
    std::cout << __func__ << "\n"; 
} 
void print_array() { 
    std::cout << __func__ << "\n"; 
} 
int read_prompt() { 
    Args args; 
    while(std::cout << "customers> " && std::cin >> args) { 
     try { 
      if(args.at(0) == "add") { 
       NewCustomer(
        boost::lexical_cast<int>(args.at(1)), 
        args.at(2), 
        args.at(3)); 
      } else if (args.at(0) == "print") { 
       print_array(); 
      } else if (args.at(0) == "remove") { 
       RemoveCustomer(boost::lexical_cast<int>(args.at(1))); 
      } else if (args.at(0) == "quit") { 
       return 0; 
      } else { 
       throw 1; 
      } 
     } catch(boost::bad_lexical_cast&) { 
      std::cout << "Error!\n"; 
     } catch(std::out_of_range&) { 
      std::cout << "Error!\n"; 
     } catch(int) { 
      std::cout << "Error!\n"; 
     } 
    } 
} 

int main() { 
    read_prompt(); 
} 
+0

所以,我錯過了 – 2013-02-15 20:36:59

相關問題