C++ How to read more integers in one line in a function?

Viewed 6717

I have a function currently that reads one integer, and checks for errors (too big too small or not an integer.

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

How can I transform this function, so that it can read more than 1 integer in one line?

Example input: 1 2

Or maybe how can I use this function 2 times for one line

3 Answers

How about std::cin and reading two variables?

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

Input:

1 5

Output:

Value 1: 1
Value 2: 5

You may also use more than 2 integer values:

int x;
int y;
int z;

cin>>x>>y>>z;

And comparing them if they're too large or small is just like any other scenario:

cin>>x>>y;

if(x > 10)
    cout<<x<<" is Greater than 10\n";

if(y > 10)
    cout<<y<<" is Greater than 10\n";

The important thing to say here I think is that the >> operator by default extracts from the stream (stdin in your case) all characters until the next whitespace. So if in the standard input you write 1 2 you need two calls to the >> operator to read both 1 and 2. They don't need to be on the same line in the code, though.

If you need to check one number at once, you may just call again your function. Take this example:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    int x;
    string str;

    getline(std::cin, str);
    stringstream ss(str);

    while (! ss.eof()) {
        ss >> x;
        cout << "Num: " << x << endl;
    }
    return 0;
}

This code reads a single line of input with getline and stores it in the string str. Then it creates a stringtream with a copy of this line and in the while loop it extracts one number at once (it stops character extraction at each whitespace) until the stream is empty. The loop is hence executed once per number in input.

If you give in input:

1 2 3 4

You get:

Num: 1
Num: 2
Num: 3
Num: 4

So you may insert your function in a similar code and call it inside the loop.

My main problem is investigating errors.

Related