0

I am a beginner in C++ and just started learning vectors.

Can someone suggest me a better way to take in values for a vector ? Or is this method good enough ? Thanks in advance :')

vector<int> vec;
int temp;
bool condition=true;
while(condition){

    cin >> temp;
    vec.push_back(temp);
    if(cin.get()=='\n') condition = false;

    }
Shubham Anand
  • 128
  • 10

2 Answers2

0

A more C++ish way would probably be to use std::getline to read the line into a std::string. Then put that string into an std::istringstream, from which you then use std::istream_iterator to fill the vector.

Perhaps something like

// Somewhere to put the text we read
std::string line;

// Read the actual text
std::getline(std::cin, line);

// A stream to parse the integers from
std::istringstream iss(line);

// Define the vector, initializing it from stream iterators
// This is a more succinct version of a loop which extracts (with `>>`)
// integers and pushes them into the vector
std::vector<int> vec(std::istream_iterator<int>(iss), std::istream_iterator<int>());

After this vec is filled with integers from a single line of input.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
-1

May be you can use C++ stream functions to check whether input stream is good enough to take input from,

while(cin.good())
{
    int i;
    cin >> i;
    vec.push_back(i);
}

That's it!

Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18
  • 2
    Doing `while (cin.good())` is no better than `while (!cin.eof())` [which is almost always wrong](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) (including this case). – Some programmer dude Jul 11 '17 at 11:08