I have a simple code which lets you input two numbers and it finds the sum. I want to stop people entering a letter when they are suppose to enter a number, so i want it to shut down if a letter is entered. I tried checking if x is not 0 through to 9, but if i inputted a two digit number, it would also shutdown. Here is the code.
#include <iostream>
#include <conio.h>
int main()
{
char vari = 0;
do
{
int x = 0;
int y = 0;
system("cls");
std::cout << "Choose a number: ";
std::cin >> x;
system("cls");
std::cout << "Choose a second number: ";
std::cin >> y;
system("cls");
int sum = x + y;
std::cout << "The sum of " << x << " and " << y << " is " << sum << std::endl << std::endl;
std::cout << "Press ENTER to restart or ESC to exit.";
if ( vari == 27 )
{
return 0;
}
std::cin.clear();
std::cin.ignore(255, '\n');
vari = _getch();
}
while( vari == 13 );
return 0;
}
#include <iostream>
#include <conio.h>
#include <string>
#include <sstream>
int GetNumber(std::string prompt = "Please enter a valid number: ")
{
std::string input;
int number = 0;
while (true)
{
std::cout << prompt;
getline(std::cin, input);
std::stringstream ss(input);
if (ss >> number)
break;
std::cout << "Invalid number, please try again" << std::endl;
}
return number;
}
int main()
{
char vari = 0;
do
{
int x = 0;
int y = 0;
x = GetNumber();
y = GetNumber("Please enter a second number: ");
int sum = x + y;
std::cout << "The sum of " << x << " and " << y << " is " << sum << std::endl << std::endl;
std::cout << "Press ENTER to restart or ESC to exit.";
if ( vari == 27 )
{
return 0;
}
std::cin.clear();
std::cin.ignore(255, '\n');
vari = _getch();
}
while( vari == 13 );
return 0;
}
Grey Wolf, your method does not allow for other data types. My method allows for any data type. The only problem is that with strings, it will not act like getline() and will only get the first piece of your string.