[英]C++ How to check the number of the input from Shell?
以下是我的C ++代码:
void test(int array[], int length) {
int index; // the index of heap array that human want to modify
int num; // the number of heap in the index position
cout << "input the index and num" << endl << flush;
string si,sj;
try{
cin >> si >> sj;
index = stoi(sj);
num = stoi(si);
}catch(std::exception e){
cout << "error, try again" << endl;
test(array, length);
}
if (index <= length && index > 0 && num > 0 && num <= array[index - 1]) {
array[index - 1] -= num;
// print(array, length);
} else {
cout << "error, try again" << endl;
test(array, length);
}
}
现在有一个运行该代码的shell,但是在shell中,存在如下输入:
输入索引和数字2 1
这是正确的
输入索引和数字2
它只有1个值,并且程序在这里阻塞以等待其他输入,我应该弄清楚并输出“错误,请重试”
输入索引和数字1 2 3
这也是不正确的,因为有两个以上的输入值。 同样,我应该弄清楚并输出“错误,然后重试”
该如何处理?
您应该使用cin.getline
作为输入。
然后将字符串拆分为子字符串并计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.