What you need is just a simple check of return value of std::getline
and operator>>
:
std::cout << "Input a string: ";
std::string inputString = "";
float inputFloat = 0.0;
if (std::getline(std::cin, inputString) &&
std::istringstream(inputString) >> inputFloat) {
std::cout << "Succesfully read float: " << inputFloat;
}
else {
// TODO: either getline failed to read string or >> failed to extract float
}
note that std::istringstream(inputString) >> inputFloat
constructs a temporary string stream and uses the appropriate overload of >>
designed specially to extracting float
values from it. Checking the return value additionally ensures that by the time the inputFloat
is outputted, it has been successfully retrieved from the stream and contains valid value.