Hi. I'm a beginner at c++ and I am making a calculator program. It is supposed to catch if the user enters invalid input but at the end of each calculation, it displays the error message. How do I make it not do that and how would I make it so that it would catch strings when it's a float?
#include <iostream>
#include <math.h>
std::string operation;
int i = 0;
double x;
double y;
void get_x_and_y();
int main() {
std::cout<<"This is a basic two number calculator\nx and y are real numbers ONLY.\nEntering a string will crash the program\n"
<<"Enter the operation\n1. x+y\n2. x-y\n3. xy\n4. x/y\n5. x^y\n6. sqrt(x)\nOperation(To add, type 1): ";
while(i<1){
getline(std::cin, operation);
if (operation=="1" || operation=="2"|| operation=="3" ||operation=="4" || operation=="5" || operation=="6"){
if (operation == "1"){
get_x_and_y();
std::cout<<x<<" + "<<y<<" = "<<x+y<<std::endl;
}
if(operation == "2"){
get_x_and_y();
std::cout<<x<<" - "<<y<<" = "<<x-y<<std::endl;
}
if(operation == "3"){
get_x_and_y();
std::cout<<x<<" * "<<y<<" = "<<x*y<<std::endl;
}
if(operation == "4"){
get_x_and_y();
std::cout<<x<<"/"<<y<<" = "<<x/y<<std::endl;
}
if(operation == "5"){
get_x_and_y();
std::cout<<x<<"^"<<y<<" = "<<pow(x,y)<<std::endl;
}
if(operation == "6"){
std::cout<<"Enter x: ";
std::cin>>x;
std::cout<<"squrt(x)"<<" = "<<sqrt(x)<<std::endl;
}}
else{
std::cout<<"INVALID INPUT";
}
}}
void get_x_and_y(){
std::cout<<"Enter x: ";
std::cin>>x;
std::cout<<"Enter y: ";
std::cin>>y;
}
#include <iostream>
#include <math.h>
std::string operation;
int i = 0;
double x;
double y;
void get_x_and_y();
int main() {
std::cout<<"This is a basic two number calculator\nx and y are real numbers ONLY.\nEntering a string will crash the program\n"
<<"Enter the operation\n1. x+y\n2. x-y\n3. xy\n4. x/y\n5. x^y\n6. sqrt(x)\nOperation(To add, type 1): ";
while(i<1){
getline(std::cin, operation);
if (operation=="1" || operation=="2"|| operation=="3" ||operation=="4" || operation=="5" || operation=="6"){
if (operation == "1"){
get_x_and_y();
std::cout<<x<<" + "<<y<<" = "<<x+y<<std::endl;
}
if(operation == "2"){
get_x_and_y();
std::cout<<x<<" - "<<y<<" = "<<x-y<<std::endl;
}
if(operation == "3"){
get_x_and_y();
std::cout<<x<<" * "<<y<<" = "<<x*y<<std::endl;
}
if(operation == "4"){
get_x_and_y();
std::cout<<x<<"/"<<y<<" = "<<x/y<<std::endl;
}
if(operation == "5"){
get_x_and_y();
std::cout<<x<<"^"<<y<<" = "<<pow(x,y)<<std::endl;
}
if(operation == "6"){
std::cout<<"Enter x: ";
std::cin>>x;
std::cout<<"squrt(x)"<<" = "<<sqrt(x)<<std::endl;
}}
else{
std::cout<<"INVALID INPUT";
}
}}
void get_x_and_y(){
std::cout<<"Enter x: ";
std::cin>>x;
std::cout<<"Enter y: ";
std::cin>>y;
}