cin是在这种情况下使用的正确函数吗
Is cin the right function to use in this scenario?
下面是我的代码的一小段:
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等于英里/小时,lname等于Daffy。在这个函数接收到所有三个变量后,它再次调用自己并重新调用用户,然后Duck输入其中的"Error!"显然得到了输出。
当用户输入此错误时,我将如何捕捉它?cin是这方面最好的功能吗?我确实查找了getline(),但我有点不确定如何实现它。
如果是我,
- 我会一次读取整行,并使用
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();
}
相关文章:
- 在这种情况下,java对象是否可以调用本机函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 在这种情况下,如何传递成员函数而不是函数?
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在这种情况下,工会成员会调用自己的析构函数吗
- 在这种情况下,如何在基类中设计开关大小写函数
- 为什么在这种情况下调用非常量右值移动构造函数?
- 为什么在这种情况下不能将 Max 用作函数?
- 在这种情况下,我可以避免使用带有主体的纯虚函数吗?
- 在这种情况下,有没有办法用单个解决方案替换两个仅在类型上不同的相似函数?
- 为什么在这种情况下不调用我的移动构造函数?(首先分配 r 值引用并创建对象)
- 在这种情况下,函数完成后的内存如何在C++中释放
- 错误 C2156:杂注必须在函数之外 - 为什么在这种情况下会发生这种情况
- 为什么在这种情况下不调用最合适的构造函数?
- 在这种情况下,我的派生类是否还需要一个虚拟析构函数
- 为什么在这种情况下调用复制构造函数和赋值运算符
- 在这种情况下,我们需要禁用默认的复制构造函数和赋值运算符
- 在这种情况下,我是否需要调用矢量的析构函数
- 为什么在这种情况下不调用复制构造函数
- 在这种情况下,为函数赋值有什么用