C++ cin是在这种情况下使用的正确功能吗?
下面是我的一段代码:C++ cin是在这种情况下使用的正确功能吗?,c++,input,getline,cin,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,f
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;
}
int读取提示(){
字符串提示,fname,lname,input;
int-id;
cout>提示;
如果(提示比较(“添加”)==0){
cin>>id;
cin>>fname;
cin>>lname;
新客户(id、fname、lname);
}else if(prompt.compare(“print”)==0){
打印数组();
}else if(prompt.compare(“remove”)==0){
cin>>id;
删除客户(id);
}else if(prompt.compare(“quit”)==0){
返回0;
}否则{
如果是我
- 我会立即读入整行代码,并使用
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();
}
#包括
#包括
#包括
#包括
#包括
typedef std::vector Args;
std::istream&operator>>(std::istream&is、Args&Args){
std::字符串s;
if(std::getline(is,s)){
标准:istringstream iss;
args.clear();
while(iss>>s)
args.向后推_(s);
}
回报是;
}
void NewCustomer(int,std::string,std::string){
std::为什么不创建一个菜单驱动程序,允许用户通过输入单个数字选择所需的功能,然后使用开关
。这样可以避免许多错误和验证代码。cin
不是一个函数,而是一个对象。因此,它有成员函数,也有可以使用它的自由函数。其中许多是提取器,即运算符>>
的重载。