简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM