I need to write a small program to calculate the volume and surface area of ​​the cube along the edge. But it is necessary to take into account that if the user enters not a number, the program should give another attempt ... Please write how to do it without errors

#include <iostream> #include <cstdlib> using namespace std; int main() { int a, V, S; setlocale(0, ""); { cout << "Введите длину ребра куба: "; cin >> a; } V = a * a * a; S = (a * a) * 6; cout << "\nV=" << V; cout << "\nS=" << S << endl; system("PAUSE"); while(1) { if (isNumber(a)) break; else cin >> a; } } 
  • And why do you have to check after calculations? - Vladimir Martyanov
  • Yes, perhaps you are right. Even if I rearrange, he will write ... [Error] 'isNumber - Mary
  • for example isdigit - Grundy
  • instead isNumber - Grundy
  • Thank you, Grundy! - Mary

1 answer 1

After trying to enter a number, check the result of the function fail() . If the input was not successful, clear() failure flag with clear() , skip the characters to the end of the line, and read the number again.

 #include <iostream> #include <limits> int main() { int x; while ((std::cin >> x).fail()) { if (std::cin.eof() || std::cin.bad()) return 1; // Входной поток закончился или помер, дальше читать смысла нет. std::cout << "error, try again\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } std::cout << "V=" << x*x*x; }