Soumadeep Saha
Soumadeep Saha

Reputation: 335

How to take input of space seperated integers in an array (c++)

Suppose I have to take input of N integers (previously provided by the user) and enter them into an array directly. For example

cin >> a >> b;

is given the input

5 10

5 is assigned to a and 10 to b.

I want a similar thing with arrays. Please help.

Upvotes: 3

Views: 3186

Answers (2)

progrenhard
progrenhard

Reputation: 2363

for(int i = 0; i < n; i++){
    cin>> array[i] >> array2[i];
}

Upvotes: 0

James Kanze
James Kanze

Reputation: 153919

If the list of integers is in a single line, and there is nothing else in that line:

std::vector<int>
getLineOfInts( std::istream& source )
{
    std::string line;
    std::getline( std::cin, line );
    std::istringstream s( line );
    std::vector<int> results;
    int i;
    while ( s >> i ) {
        results.push_back( i );
    }
    if ( ! s.eof() ) {
        //  Syntax error in the line...
        source.setstate( std::ios_base::failbit );
    }
    return results;
}

Upvotes: 4

Related Questions