Переменная cafContent
будет всегда иметь тип double
, что весь смысл объявлений и строгой типизации.
То, что вы, похоже, хотите, это сделать подтверждение ввода . Это проще всего сделать, проверив состояние самого потока. Помня, что операции ввода возвращают ссылку на объект потока, и что потоки имеют оператор преобразования bool
, мы могли бы сделать что-то вроде
cout << "Enter milligrams of caffeine: ";
while (!(cin >> cafContent))
{
if (cin.eof())
{
// TODO: User wanted to terminate, handle it somehow
}
// An error, most likely not a number entered
cout << "You must enter a number.\n";
cout << "Enter milligrams of caffeine: ";
// We must clear the state of the stream to be able to continue
cin.clear();
// Also since the user might have added additional stray text after the input
// we need read it and throw it away
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
// Here a number have been entered, do something with it