我正在尝试从命令提示符读取有效的用户输入:
例如,有效的用户输入格式如下:
getData <>
<> -任何字符串类型值
在命令提示符下:
例如,getData name =>正确( getData后只输入一个参数,不出所料)例如getData name ID => InCorrect (在getData后输入多个参数)例如getData => InCorrect (由于在getData后没有输入参数)
如何检查参数的数量?我的代码逻辑如下:
string cmd_input;
getline(cin, cmd_input)
stringstream ss(cmd_input);
string input;
string parameter;
ss >> input; //getData
ss >> parameter; //name如何进行有效/无效检查?我不想通过循环运行它直到EOF流,并计算参数的数量。我在peek()上读过,但不确定它是否适合这里。另外,我不想使用向量来存储参数。
谢谢!
发布于 2013-10-05 06:03:37
您可以在检索输入后检查流本身的状态。如果检索成功,则为true。您希望它在两次检索后返回true,但在第三次检索时返回false。
if (!(ss >> input1) || input1 != "getData") { //... error : unexpected cmd
}
if (!(ss >> input2)) { //... error: no param
}
if (ss >> input3) { //... error: too many params
}
//... okay发布于 2013-10-05 06:05:05
在不使用循环甚至不使用std::vector的约束下,它可能看起来如下所示:
std::string line, command, arg1, arg2, arg3;
if (std::getline(std::cin, line)) {
std::istringstream is(line);
if (is >> command) {
std::string word;
if (is >> arg1) {
...
if (is >> arg2) {
...
if (is >> arg3) {
...
}
}
}
} // end of is >> command
}然而,如果您改变主意并决定使用std::vector,它可能如下所示:
std::string line, command;
std::vector<std::string> arguments;
if (std::getline(std::cin, line)) {
std::istringstream is(line);
if (is >> command) {
std::string word;
while (is >> word)
arguments.push_back(word);
}
}发布于 2013-10-05 06:03:55
ss >> input;
if( ss.eof() )
//no parameter code
else
{
ss >> param;
if( !ss.eof() )
// too many param code
else
// good input
}https://stackoverflow.com/questions/19191410
复制相似问题