lkkeepmoving
lkkeepmoving

Reputation: 2355

when inputing data from keyboard, how to complete input when user press "enter" in C++?

The problem is, in C++, I hope to get numbers from user and put every int to an vector. So I write the following code:

#include <iostream>
#include <vector>
using namespace std;

vector<int> readVals()
{
    vector<int> read;
    int temp;
    cin >> temp;
    while (!cin.fail() && !cin.eof())
        {
            read.push_back(temp);
            cin >> temp;
        }
    return read;
}

void printVals(vector<int> v)
{
    if(v.size() >= 1)
        {
            for (vector<int>::size_type i = 0; i < v.size()-1; i++ )
        {
            cout << v[i] << " ";
            cout << v[v.size()-1] << "\n";
        }
    }
}

int main()
{
    vector<int> a = readVals();
    printVals(a);
    return 0;
}

Then, I compile it to create an a.out file. I have some numbers in in1. And when I do the command: a.out < in1, I got what I want. But I'm confused when I hope the data can be inputted by user. The user can input some numbers and press Enter to pass the numbers in. However, I used getline(), failed. !="\n", failed. Everytime when I press Enter, it seems that the program is still waiting for more numbers and not print out the result. Does any one can help me to make it successfully? Thank you!

Upvotes: 1

Views: 626

Answers (1)

Cogwheel
Cogwheel

Reputation: 23217

Your loop is waiting for cin to be in a "failed" state or at the end of file. Hitting enter does neither. You can end the input by hitting CTRL-Z on windows or CTRL-D on unix/mac. These send the "End of file" character to cin. Alternatively, change your loop condition to "listen" for some specific input.

Upvotes: 4

Related Questions