Amaresh Kumar Sharma
Amaresh Kumar Sharma

Reputation: 763

why does not std:cin recognise enter key

I am trying to take input from command prompt and put every input separated by white-space or tab to vector until user presses "enter". I am not able to do do. here is my code

template <typename T> 
vector <T> process_input_stream() {

    T value;
    vector <T> vect;

    string line;
    //read input and populate into vect until return key is pressed
    while (getline(cin, line, '\n')){
        cin >> value;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
        vect.push_back(value);
    }

    return vect;
}

now the problem i am hitting my head to, is, when entering input, input is screen is still asking for more input even after pressing enter key.

Upvotes: 0

Views: 158

Answers (1)

Sid S
Sid S

Reputation: 6125

The line variable contains the whole line, except the linefeed.

To parse each line, you could replace your while loop with:

while (getline(cin, line))
{
    istringstream iss(line);
    while (iss >> value)
    {
        vect.push_back(value);
    }
}

Upvotes: 3

Related Questions