首页 > 解决方案 > 忽略输入行中的某些输入

问题描述

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

这个“ep 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));

标签: c++

解决方案


我建议这个解决方案不使用 cin.fail(),而是使用字符串、stoi 和 try catch 块。

#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));
}

推荐阅读