Anonymous Entity Anonymous Entity - 9 months ago 53
C++ Question

Get only the first value from std::cin

When reading some input from

I want to allow only a single numeric entry. So given the code

float n = 0;
std::cin >> n;

how would I then identify the case where the user input something like
1 2 3

Answer Source

Use getline and istringstream and run while loop to count number of integers entered:

string line;
getline(cin, line);
int x, cnt = 0;
istringstream iss(line);
while(iss >> x){

cnt would be 3 for 1 2 3.