cin是在这种情况下使用的正确函数吗

Is cin the right function to use in this scenario?

本文关键字:函数 这种情况下 cin      更新时间:2023-10-16

下面是我的代码的一小段:

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();
}