忽略一行输入中的某些输入

Ignore certain inputs in a line of inputs

本文关键字:输入 一行      更新时间:2023-10-16

我正在制作一个只接受整数对输入的函数。这将在 while 循环中重复,直到用户输入 "-5 -5"。如果我输入"5 7 -4 3 10 1 -2 0 -5 -5",它将全部作为有效输入。如果输入中有像"e p 5 7 -4 3 10 1 -2 0 -5 -5"这样的字符,我的代码将忽略"e p 5 7 -4 3 10 1 -2 0 -5 -5"的整个输入。相反,我只想跳过第一对"e p",仍然保留其余的。

这个呢,"e p erewr djfe -4 3 ekjea 23 -2 0 -5 -5"?在这种情况下,我只想要" -4 3 -2 0 -5 -5"。我怎样才能做到这一点?谢谢。

这是我的代码:

int input1 = 0;
int input2 = 0;
do {
cin >> input1 >> input2;
if (cin.fail()) {   // This will handle non-int cases
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
} else {
setValues(input1, input2);
}
} while((input1 != -5 && input2 != -5));

我提出这个解决方案没有cin.fail((,但使用strings,stoi并尝试捕获块。

#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main()
{
string input1;
string input2;
int in1,in2;
bool ok=false;
bool ok2=false;
bool ignore=false;
do
{
ok=false;
cin>>input1;
try
{
in1=stoi(input1);
ok=true;
}
catch(...)
{
}
cin>>input2;
ok2=false;
if(ok)
{
try
{
in2=stoi(input2);
ok2=true;
}
catch(...)
{
}
if(ok2) 
setValues(in1,in2);
}
}
while((in1 != -5 && in2 != -5));
}