cin是否适合在这种情况下使用?

时间:2013-02-15 19:50:27

标签: c++ input getline 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;

}

只要用户没有输入任何意外的内容,这就可以正常工作。其中一个测试用例应该通过输入“添加125mph Daffy Duck”,其中id最终为125,fname等于mph,lname等于Daffy。在此函数接收到所有三个变量后,它再次调用自己并重新提示用户,然后输入Duck,其中“Error!”明显得到输出。

用户输入错误后如何捕获此错误?在这方面cin是最好的功能吗?我确实查找了getline(),但我有点不确定如何实现它。

1 个答案:

答案 0 :(得分: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();
}