2013-02-15 77 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

相关问题