c++ - C ++如何在函数的一行中读取更多整数?
问题描述
我目前有一个读取一个整数的函数,并检查错误(太大太小或不是整数。
int be_egesz(string question, int minval, int maxval, string error_message)
{
bool error;
string tmp;
int number;
do
{
cout << question << endl;
cin >> szam;
error=cin.fail() || cin.peek()!='\n' || (number<minval || number>maxval);
if (error)
{
cout << error_message << endl;
}
cin.clear();
getline(cin,tmp,'\n');
}while(error);
return number;
}
如何转换此函数,使其可以在一行中读取 1 个以上的整数?
示例输入:1 2
或者也许我怎样才能在一行中使用此功能 2 次
解决方案
如何std::cin
读取两个变量?
#include <iostream>
using std::cout;
using std::cin;
int main() {
int x;
int y;
cin>>x>>y;
cout<<"Value 1: "<<x<<"\n"<<"Value 2: "<<y<<"\n";
return 0;
}
输入:
1 5
输出:
Value 1: 1
Value 2: 5
您还可以使用超过 2 个整数值:
int x;
int y;
int z;
cin>>x>>y>>z;
如果它们太大或太小,比较它们就像任何其他情况一样:
cin>>x>>y;
if(x > 10)
cout<<x<<" is Greater than 10\n";
if(y > 10)
cout<<y<<" is Greater than 10\n";
推荐阅读
- python - 通过python opencv从图像中提取模式
- python - SyntaxError:无效语法:python -c“import numpy”
- regex - 需要提取在特定正则表达式的响应中找到的所有值
- android - 创建 SpalshScreenActivity 时图像被像素化和拉伸
- ios - 有没有解决方案从 xcode 项目中删除 lint 以及所有相关的东西?
- jquery - 如何对ajax加载的内容执行jquery每个功能?
- python-3.x - 尝试通过 pykafka 连接到 kafka 时,在所有 docker 映像中出现 import _rd_kafka 错误
- node.js - Shopify React Next 无法读取未定义的属性“/_app”
- javascript - 如何使标签栏粘在页面底部?
- firebase - 如何从firestore中检索经纬度?