Get a Number and prints their square roots, until the user either presses 0 or presses ENTER directly after the prompt - C++ File Stream

C++ examples for File Stream:cin

Description

Get a Number and prints their square roots, until the user either presses 0 or presses ENTER directly after the prompt

Demo Code

#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
double get_number();
int main()// w w w .ja  va2 s.com
{
   double x = 0.0;
   while(true) {
      cout << "Enter a num (press ENTER to exit): ";
      x = get_number();
      if (x == 0.0) {
         break;
      }
      cout << "Square root of x is: " << sqrt(x);
      cout << endl;
   }
   return 0;
}
double get_number() {
   char s[100];
   cin.getline(s, 100);
   if (strlen(s) == 0) {
      return 0.0;
   }
   return atof(s);
}

Result


Related Tutorials