1

I'm trying to make a program that takes input from the console, and reads each words and numbers separated by spaces and stores it in a vector string for further processing.

void foo() {
    string input;

    vector<string> list;




    while (getline(cin, input, ' '))
    {
        list.push_back(input);
    }

    for (int counter = 0; counter < list.size(); counter++) 
    {
        cout << list[counter] << endl;
    }

};




int main()
{

    foo();

    return 0;
}

The problems comes when getline doesn't stop reading at newlines and you need to ctrl+z to EOF. Is there anyway to make getline stop at newline?

Emil Laine
  • 41,598
  • 9
  • 101
  • 157

2 Answers2

1

First get the line, then use istringstream to extract strings in it.

string line;
getline(cin, line);
istringstream iss(line); //need <sstream>
vector<string> inputStrings;
for (string s; iss >> s; inputStrings.push_back(s));
tnt
  • 1,174
  • 2
  • 10
  • 14
0

This kind of things usually can be expressed better with the standard library:

#include <iterator>
#include <iostream>
#include <vector>

int main(int argc, char** argv) {
    std::vector<std::string> list;
    std::copy(std::istream_iterator<std::string>(std::cin),
            std::istream_iterator<std::string>(),
            std::back_inserter(list));
}
mshrbkv
  • 309
  • 1
  • 5