Anonymous Entity Anonymous Entity - 1 month ago 6
C++ Question

Get only the first value from std::cin

When reading some input from

std::cin
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

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++;
}

cnt would be 3 for 1 2 3.