Change to:
// Ensure extraction suceeded and the whole line was consumed.
// This will detect invalid inpts such as "1.17abc",
// whereas if eof() was not present "1.17abc" would be
// considered valid with a value of "1.17".
//
if (Str_variable >> variable && Str_variable.eof())
{
break; // and just use while (true) instead.
}
else
{
std::cerr<< "Incorrect input: " << line << ". Please try again" << std::endl;
}
to check the result of the extraction as opposed to the value of the variable after the extraction. In the posted code, when 0
is entered the if (variable)
branch is not entered due to the condition failing.
Additionally, see strtof()
for an alternative.