Last active
October 10, 2015 10:07
-
-
Save soachishti/1316b5a7cf6f9718c362 to your computer and use it in GitHub Desktop.
Input only numbers, using getch()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Name: Syed Owais Ali Chishti | |
* Roll No: P14-6011 | |
* Major: BS(CS) | |
* Course: Computer Programming Lab | |
* Task: 001 | |
*/ | |
#include<iostream> | |
#include<conio.h> // _getch() | |
#include<string> | |
#include<math.h> | |
using namespace std; | |
/* | |
* Prototype Function | |
*/ | |
void cinNumeric(double &num); | |
/* | |
* Main | |
*/ | |
void main() { | |
double num[3] = {0}; | |
double choice; | |
for (int i = 0; i < 3 ; i++){ | |
string kbData = ""; | |
cout << "Input " << i+1 << " number: "; | |
cinNumeric(num[i]); | |
cout << endl; | |
} | |
cout << endl; | |
cout << "Select any option" << endl; | |
cout << "1: Sum" << endl; | |
cout << "2: Average" << endl; | |
cout << "3: Multiply" << endl; | |
cout << "Choice: "; | |
cinNumeric(choice); | |
cout << endl; | |
if (choice == 1) { | |
double sum = num[0] + num[1] + num[2]; | |
cout << "Sum = " << num[0] << " + " << num[1] << " + " << num[2] << " = " << sum; | |
} | |
else if (choice == 2) { | |
double average = (num[0] + num[1] + num[2]) / 3; | |
cout << "Average = (" << num[0] << " + " << num[1] << " + " << num[2] << ") / 3 = " << average; | |
} | |
else if (choice == 3) { | |
double product = num[0] * num[1] * num[2]; | |
cout << "Multiplication = " << num[0] << " x " << num[1] << " x " << num[2] << " = " << product; | |
} | |
else { | |
cout << "Invalid Choice, Terminating."; | |
} | |
cout << endl; | |
} | |
/* | |
* Return only numeric to reference variable. | |
*/ | |
void cinNumeric(double &num){ | |
string kbData = ""; | |
char ch; | |
while (kbData.empty()) { | |
//Continue if contain value; | |
while (int( ch = _getch()) != 13) { | |
//Catching only integers between 0(48) - 9(57) and 46 for point (.) | |
if (ch >= 48 && ch <= 57 || ch == 46) | |
{ | |
kbData += ch; | |
cout << ch; | |
} | |
if (ch == 8) { | |
kbData.erase(kbData.end()-1,kbData.end()); | |
cout << "\b \b"; | |
} | |
} | |
} | |
//convert string to double. Function from std library | |
num = atof(kbData.c_str()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment