首页 > 解决方案 > 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 次

标签: c++cin

解决方案


如何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";

推荐阅读