c++ - 忽略输入行中的某些输入
问题描述
我正在制作一个只接受一对整数输入的函数。这将在 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));
解决方案
我建议这个解决方案不使用 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));
}
推荐阅读
- redis - 如何停止匿名访问redis数据库
- mongodb - 查询 MongoDB 中的多个计数
- jenkins - 如何避免在 Jenkins 中插值敏感变量
- javascript - Flask SocketIO 不适用于 socketio javascript
- sql-server - 如何确定 MaxEnvelopeSizekb 的正确大小(或至少是一个好的估计)?
- asp.net-core - 使用 Firebase 发送推送通知 - 无效授权:未找到帐户错误
- python - 如何计算相关性分数?
- html - 子 div 占用超过 100% 的父级忽略兄弟姐妹的位置和溢出容器
- html - Bootstrap 4,CSS - 在选项卡菜单上隐藏文本
- python - 是否可以使用 shutil.copy() 制作文件的多个副本?