Nishchay
Nishchay

Reputation: 41

How to accept space separated integers and store them in a vector in C++?

I tried to accept N spaced integers, store them in a vector and print them. This is my code:

#include <string>
#include <vector>

using namespace std;
int main() {
  string rawInput;
  vector<string> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }
  for (int j = 0; j < sizeof(numbers)/sizeof(numbers[0]); ++j) {
    cout << numbers[j] << " ";
  }
}

It doesn't work. I get no output after running this code. Please give an example with floating point numbers and integers. Please tell me how to print them as well. Thank you.

Upvotes: 0

Views: 2754

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57678

For space separated integers, don't use getline. The newline counts as space when constructing integers.

Try something like this:

std::vector<int> database;
int number;
while (cin >> number)
{
    database.push_back(number);
}

You may want ask yourself if there really is a need to read a line of integers (or if any kind of record is delineated by a newline).

Edit 1: Reading space separated integers by text line
If you must read by line, one method is to use std::istringstream:

std::vector<int> database;
std::string text_line;
while (getline(cin, text_line))
{
    int number;
    std::istringstream line_stream(text_line);
    while (line_stream >> number)
    {
        database.push_back(number);
    }
}

IMHO, reading by line adds an unnecessary level of complexity.

Upvotes: 3

Related Questions