C++ Loop back beginning if the result is false - c++

I am very new to C++ and still studying. The below scenario just came to my mind and I was trying to figure it out how to do this.
Scenario is as below:-
User inputs a number
then I store it in x
next is to check whether the input number is an int or float
if int, then pop up a message "Entered Number is not a Decimal Number" and go back to the beginning and inform the user to re-enter a number
if the entered number is float then I round it to the nearest int and pop up a message cout<<"Nearst Rounded Number is : "<<round(x)<<endl;
I assume this can be done with a loop, but I cannot figure it out.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float x,y;
cout<<"Enter Number Here : ";
cin>>x;
{
if ( (x- int(x) == 0))
cout<<"Entered Number is not a Decimal Number"<<endl<<endl;
else
cout<<endl;
cout<<"Nearst Rounded Number is : "<<round(x)<<endl;
}
}

while(true) {
//(your existing code goes here)
cout << "Do you want to run the program again either types yes or no" << endl;
cin >> answer;
if (answer != 'yes' && answer != 'Yes')
break;
}
It should work. Else you can keep one bool variable in if else part and validate them below and break the while loop until your condition satisfy.

I believe this is what you wanted:
int main() {
string input_str;
float input_float = 0;
while (true) {
cout << "Enter number here: ";
cin >> input_str;
input_float = stof(input_str); //stof converts string to float
if (input_float != 0) {
if (input_float == int(input_float)) cout << "Entered number is not a decimal, please try again." << endl;
else break;
}
//TODO: Catch any exceptions thrown by stof (Ex: User inputs a letter)
}
cout << "Nearest Rounded number is: " << round(input_float)<<endl;
return 0;
}
Bye!
Edit: Changed the code a bit and removed a bug.

I have changed your code a bit to take input continuously. while(cin>>x) means the program is taking input constiniously until EOF. Then when you find a decimal number, it breaks.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float x,y;
cout<<"Enter Number Here : ";
while(cin>>x)
{
if ( (x- int(x) == 0))
cout<<"Entered Number is not a Decimal Number"<<endl<<"Enter Number Here : ";
else
{
cout<<"Nearst Rounded Number is : "<<round(x)<<endl;
break;
}
}
}
By the way I will advise you to spend a bit more time to find out the solution on your own before posting here.

first of all Why is “using namespace std;” considered bad practice?
second - use a loop with a boolean flag to indicate when you want the exit the loop
#include <iostream>
#include <cmath>
int main()
{
float x,y;
bool flag = true;
while(flag)
{
std::cout<<"Enter Number Here : ";
std::cin>>x;
{
if ( (x- int(x) == 0))
std::cout<<"Entered Number is not a Decimal Number"<<std::endl;
else{
std::cout<<std::endl;
std::cout<<"Nearst Rounded Number is : "<<round(x)<<std::endl;
flag = false;
}
}
}
}

Your code needs improvements like indentations and the use of loop conditions otherwise your program will not rerun again.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float x,y;
bool correctinputFlag=false;
do()
{
cout<<"Enter Number Here : ";
cin>>x;
if ( (x- int(x) == 0))
{
cout<<"Entered Number is not a Decimal Number"<<endl<<endl;
}
else
{
cout<<endl;
cout<<"Nearst Rounded Number is : "<<round(x)<<endl;
correctinputFlag=true;
}
}while(correctinputFlag==false);
}

Related

Whats a good way to get the program to end based on user input?

I did my "Hello World", I'm just getting started on my programming adventure with C++. Here is the first thing I've written, what are some ways to get it to end with user input? I'd like a yes or no option that would terminate the program. Also any feedback is welcome, thank you
#include <iostream>
using namespace std;
void Welcome();
void calculateNum();
void tryAgain();
int main() {
Welcome();
while (true) {
calculateNum();
tryAgain();
}
system("pause");
}
void calculateNum() {
float userNumber;
cin >> userNumber;
for (int i = 100; i >= 1; i--) {
float cNumber = i* userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
}
void Welcome() {
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain() {
cout << "Try again? Enter another number... ";
}
Here is one option:
Switch to do ... while loop, with the condition at the end.
Make your tryAgain() function return a boolean and put it in the while condition.
In tryAgain function read input from the user, and compare it to expected answers.
First, lets add a new header for string, it will make some things easier:
#include <string>
Second, lets rebuild the loop:
do {
calculateNum();
} while (tryAgain());
And finally, lets modify the function:
bool tryAgain() {
string answer;
cout << "Try again? (yes / no)\n";
cin >> answer;
if (answer == "yes") return true;
return false;
}
Now, there is a slightly shorter way to write that return, but it might be confusing for new learners:
return answer == "yes";
You don't need the if because == is an operator that returns bool type value.
You can change your calculateNum() in the following way:
Change the return value of your calculateNum() function into bool to indicate whether the program shall continue or stop
read the input into a std::string
check if the string is equal to your exit string like 'q' for quit
3.a in that case, your function returns false to indicate the caller that the program shall stop
3.b otherwise, create a stringstream with your string and read the content of the stream into your float variable and continue as you do like now
In your loop in your main function you break if calculateNum() returned false
Here is a simple solution:
#include <iostream>
// Here are two new Includes!
#include <sstream>
#include <string>
using namespace std;
void Welcome();
// Change return value of calculateNum()
bool calculateNum();
void tryAgain();
int main()
{
Welcome();
while (true)
{
if (!calculateNum())
break;
tryAgain();
}
system("pause");
}
bool calculateNum()
{
//Read input into string
string userInput;
cin >> userInput;
//Check for quit - string - here just simple q
if (userInput == "q")
return false;
//otherwise use a std::stringstream to read the string into a float as done before from cin.
float userNumber;
stringstream ss(userInput);
ss >> userNumber;
//and proces your numbers as before
for (int i = 100; i >= 1; i--)
{
float cNumber = i * userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
return true;
}
void Welcome()
{
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain()
{
cout << "Try again? Enter another number... ";
}
Having your users input in a string you can even do further checks like checking if the user entered a valid number, interpret localized numbers like . and , for decimal delimitters depending on your system settings and so on.

find the minimum value entered while using infinite loop c++

My task is to find the minimum number between n input values that the user should enter in an infinite loop until a certain number or character is entered to stop the loop.
The problem that I am facing is, I can't get the condition that tests the input to see which of the entered numbers is the smallest to work. Also, a second problem is, I want to end the loop with a char not an int, but I don't know if that is even possible.
I searched online but I can't find any answers.
Side note: I am new to C++. I am using Borland C++ v5.02.
#include <iostream>
#include <conio.h>
int I, min =0;
cout<<"Enter a number :";
do{
cin >> I;
if (I < min){
if (I > 0){
min = I;
}
}
}while (I > -1);
cout << min;
I solved your problem by using a try-catch block and stoi().
stoi() is used to convert a string into a number. If the number input is not convertible (meaning that a char is entered and the loop should break), const std::invalid_argument & e is catch and automatically break the loop.
#include <iostream>
using namespace std;
int main()
{
int Min = INT_MAX; string I; int x;
do
{
cout << "Enter a number or a char : ";
cin >> I;
try
{
x = stoi(I);
if (x < Min)
{
if (x > 0) {Min = x;}
}
}
catch(const std::invalid_argument & e) {break;}
}
while(x > 0);
cout << "Minimum positive number entered : " << Min;
}
Output:
Enter a number or a char : 10
Enter a number or a char : 8
Enter a number or a char : 5
Enter a number or a char : 7
Enter a number or a char : a
Minimum positive number entered : 5
As your code is a bit unclear, I changed both constraint to I>0, and you can easily modified this bit.
For the prolem with INT_MAX, maybe #include <climits> or #include <limits.h> will help, as specified here. If the problem persist, the workaround is to set Min to something high, for example 10^9.
*Note: Ran on Code::Blocks 20.03, Windows 10 64-bit.
the problem with the code was with the header I couldn't find a one that was working with my compiler Borland v5.02 c++ but thanks to #JerryJeremiah he leads me to it.
also, I redeclared the min =INT_MAX; because I am using this code in a loop.
the code is working with me now.
#include <iostream>
#include <conio.h>
#include <limits.h>
int main()
{
int I, min =INT_MAX;
cout<<"Enter number of input :";
do{
cin>>I;
if (I<min ){
if(I>0){
min =I;
}
}
}while(I>-1);
cout<<min;
min =INT_MAX;
getch();
}

Why is my C++ code wrong to calculate the maximum and minimum of integers?

I am learning the C++ programming language and I am a beginner. I had to write a code so that a user inputs a series of integers and whenever he enters -99, that should signal the end of the series and then my program needs to find the smallest and largest integers. I initially came up with this solution
#include <iostream>
using namespace std;
int main()
{
int k=0, number, maximum, minimum;
do
{
cout<<"Enter an integer: ";
cin>>number;
if (number==-99)
{
break;
}
if (k==0)
{
maximum=number;
minimum=number;
}
if (number>maximum)
{
maximum=number;
}
if (number<minimum)
{
minimum=number;
}
k++;
}
while(number!=-99);
cout<<"The smallest entered integer is "
<<minimum
<<" and the largest entered integer is "
<<maximum
<<endl;
return(0);
}
and sent it to my lecturer and asked if there is a cleaner way of doing this but he did not reply. Next, I changed this program to find the maximum and minimum using the formulas max(x,y)=(x+y+abs(y-x))/2 and min(x,y)=(x+y-abs(y-x))/2 instead using comparisons.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int k=0, number, maximum, minimum;
do
{
cout<<"Enter an integer: ";
cin>>number;
if (number==-99)
{
break;
}
if (k==0)
{
maximum=number;
minimum=number;
}
maximum=(maximum+number+abs(number-maximum))/2;
minimum=(minimum+number-abs(number-minimum))/2;
k++;
}
while(number!=-99);
cout<<"The smallest entered integer is "
<<minimum
<<" and the largest entered integer is "
<<maximum
<<endl;
return(0);
}
but this time my lecturer replied and the only thing he said was that it is wrong. I have tested both of my codes few times and they show me the correct result so I have no clue what my lecturer meant by saying it is wrong. Could someone please let me know why any of the two codes above is wrong and why?
Both of your programs work fine. If you'd like it be cleaner than you can do the following:
Check if the input succeeded before using number. You can do this by putting the input operation in a while loop.
Just use the max and min functions found in <cmath>.
This will be your program:
int main() {
int number = -100, maximum = -99, minimum = 99;
while (cin >> number && number != -99) {
maximum = max(maximum, number);
minimum = min(minimum, number);
}
if (number == -99) {
cout << "The smallest entered integer is " << minimum
<< " and the largest entered integer is " << maximum << endl;
}
}
There are several ways to correct the problem. One is to check for the value of k in your initial example to verify that a value was actually entered and that minimum and maximum are initialized.
A slightly different approach that might impress your lecturer is to initialize minimum and maximum to values that will lead to a correct result. std::numeric_limits provides the minimum and maximum values for integers. Using this you could implement something along these lines:
#include <iostream>
#include <limits>
#include <algorithm>
int main()
{
int number;
int maximum = std::numeric_limits<int>::min();
int minimum = std::numeric_limits<int>::max();
while ((std::cin >> number) && (number != -99))
{
maximum = std::max(maximum, number);
minimum = std::min(minimum, number);
}
if (std::cin)
{
if ((maximum != std::numeric_limits<int>::min()) || (minimum != std::numeric_limits<int>::max()))
{
std::cout << "maximum = " << maximum << std::endl;
std::cout << "minimum = " << minimum << std::endl;
}
else
{
std::cout << "No number entered" << std::endl;
}
}
else
{
std::cout << "Errorr reading the number" << std::endl;
}
}
The formulas used in your second code snippet are mathematically correct, but have drawbacks if used in computer programming where variables have limited range.
The first code snippet works across the entire representable set of integers (except -99 for obvious reasons).
The second code snippet will not work for inputs whose absolute value is greater than INT_MIN / -2, because the computations will overflow.
Don't feel bad, this bug is not at all obvious and a lot of programmers have overlooked it. For a related example, see:
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken
Unfortunately, if you have this kind of bug in code processing untrusted input, your range checking could fail and lead to a security vulnerability. So don't go ignoring it just because "I never expect inputs that large".
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number, maximum=0, minimum=0;
bool isDirty = false;
do
{
cout<<"Enter an integer: ";
cin>>number;
if(number!=-99){
if(isDirty==false) {
isDirty = true;
minimum = maximum =number;
} else {
if (number < minimum) {
minimum = number;
}
if (number > maximum){
maximum = number;
}
}
}
}
while(number!=-99);
cout<<"The smallest entered integer is "
<<minimum
<<" and the largest entered integer is "
<<maximum
<<endl;
return(0);
}

I need to limit my program not to accept any decimal values in my program

I am instructed that I have to reject any decimal and I need to re enter the number again.I tried this code but still it just goes to the whole process before acknowledging the error. Try the program and judge me :D here's my code:
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<limits>
using namespace std;
int getInt()
{
int m=0;
while (!(cin >> m))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Please input a proper 'whole' number: " ;
}
return (m);
}
int main()
{
double x;
int q,w,e,choice;
cout<<"Welcome! This program will sort out the integers you will input!\nPlease input number of integers: ";
cin>>q;
cout<<endl<<endl;
int* inc= new int[q];
int* dec= new int[q];
for(int p=1;p<=q;++p)
{
w=p;
e=p;
cout<<"Input integer number "<<p<<": ";
x =getInt();
while(e>0 && inc[e-1]>x)
{
inc[e]=inc[e-1];
e--;
}
while(w>0 && dec[w-1]<x)
{
dec[w]=dec[w-1];
w--;
}
inc[e]=x;
dec[w]=x;
}
cout<<endl;
cout<<"What order do you prefer? Input 1 for increasing and 2 if decreasing.\nChoice: ";
cin>>choice;
while(choice<1 || choice>2)
{
cout<<"Please input a correct choice! Try again!\nChoice: ";
cin>>choice;
}
if(choice==1)
{
for(int i=0;i<q;++i)
cout<<inc[i]<<"\t";
cout<<endl;
}
else
{
for(int i=1;i<=q;++i)
cout<<dec[i]<<"\t";
cout<<endl;
}
system("PAUSE");
}
hoping for your help :)
You can try using modulo.
Just an idea, hope it helps.
bool flag = false;
While (flag == false){
cin>>number;
if ((number % 1) != 0){
flag = false;
}
else{
flag = true;
}
cin.clear();
}
Try making a copy of the number you want to test and casting it to an int and then back to a double, and then check for equality. If they are equal, you have an int, if they are not, you have a decimal:
#include <iostream>
using namespace std;
int main()
{
double a = 5;
double c = 5.5;
double b = a;
bool test1 = (double)((int)b) == a; //true!
b = c;
bool test2 = (double)((int)b) == c; //false!
cout << test1 << endl;
cout << test2 << endl;
return 0;
}
Wrote this answer a long time ago, it is very hacky and will not work on all inputs. Use std::stoi and check if it throws as the comment suggests instead.

Take filtered user input and make it correspond to a menu option

I'm trying to build a simple one-operation calculator in order to practice techniques like while and for loops, and I'm trying to learn and understand ways to have "menus" in the console.
I've got a program that gives you a list (entries from map, a function I was able to use but know almost nothing about) of operations from which you must choose.
If you enter an invalid input (a non-integer or an out-of-range integer), it prompts you for a valid answer. Now I want the program to take the entries (1-4) and make them correspond to an operation.
You'll see in my code that each operation has its own method (I thought this would be a good way to do things, especially to practice working between methods). What I want is for main to take operatorSelection, and use that to choose which method to jump to. It will then compute result and return it to main.
I thought I might achieve that by using map, having operatorSelection correspond to an entry in map, and having that entry's corresponding string be used to call a method (where each method is named the same as in map).
Note before answering
I'm new to this and I want to know the optimized way to go about this. I want it simple, but efficient; I don't know some of the functions I'm using, especially map. I've read briefly about vector and array, but I didn't know how to make use of them. I realize map in my function seems to print in alphabetical order, and I'd like to be able to sort entries completely of my own preference. Is there a better way to go about this than with map?
Here is my code (the operation methods are incomplete, I know):
// OneOpCalc.cpp : Defines the entry pofloat for the console application.
#include "stdafx.h"
using namespace std;
int operatorSelection;
float firstNumber,secondNumber,result;
int main(float argc, char* argv[])
{
bool validInput = false;
map<string,int> Operations;
Operations.insert(pair<string, int>("Addition", 1));
Operations.insert(pair<string, int>("Division", 2));
Operations.insert(pair<string, int>("Multiplication", 3));
Operations.insert(pair<string, int>("Subtraction", 4));
cout << "Welcome to OneOpCalc. ";
while (!validInput)
{
cout << "Please select an operation by its number: ";
cin >> operatorSelection;
if (!cin || operatorSelection > 5 || operatorSelection < 1)
{
cout << "Error: Invalid entry. Try again." << endl << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else
{
validInput = true;
}
}
system("pause");
return 0;
}
float Addition (float firstNumber, float secondNumber)
{
result=firstNumber+secondNumber;
return (result);
}
float Subtraction (float firstNumber, float secondNumber)
{
result=firstNumber-secondNumber;
return (result);
}
float Multiplication (float firstNumber, float secondNumber)
{
result=firstNumber*secondNumber;
return (result);
}
float Division (float firstNumber, float secondNumber)
{
result=firstNumber/secondNumber;
return (result);
}
To put the question simply:
What is a good way to call a method depending on user input?
To answer your question: a switch would be appropriate (see below)
Other possibilities are:
A map with function pointers as Ilya Kobelevskiy has mentioned, or you use an enum for such a thing instead of the map, if you need all this at all (have a look at enums). But first let's have a look at your code:
You shouldn't use float as argc in your main. The argument count is a natural number, not a float (fracture).
Don't forget your includes:
#include <iostream> // for cin / cout
#include <map> // for the map
#include <limits> // for numeric_limits<...>
Instead of system("pause") you should better use std::cin.get(). It has the same effect but it's portable and also doesn't only work under Windows.
Instead of !cin, which is basically the same as cin == null, you probably want to use !cin.good()
If you only have 4 operations, don't allow 5 as input (you currently allow it)
Also, in your functions you're altering the global variable result which I think wasn't intented that way, was it? You can actually directly return the result without having to save it somewhere before.
Global variables are somewhat bad practice. Try to avoid these.
Here is a working example of your code that also compiles:
#include "stdafx.h" // inconvenient unportable windows stuff
#include <iostream> // cin and cout
#include <map> // the map
#include <limits> // numeric_limits
#include <string> // strings (obviously)
using namespace std;
int operatorSelection;
float firstNumber,secondNumber,result;
int main(int argc, char* argv[])
{
bool validInput = false;
map<string,int> Operations;
Operations.insert(pair<string, int>("Addition", 1));
Operations.insert(pair<string, int>("Division", 2));
Operations.insert(pair<string, int>("Multiplication", 3));
Operations.insert(pair<string, int>("Subtraction", 4));
cout << "Welcome to OneOpCalc. ";
while (!validInput)
{
cout << "Please select an operation by its number: ";
cin >> operatorSelection;
if (!cin.good() || operatorSelection > 4 || operatorSelection < 1)
{
cout << "Error: Invalid entry. Try again." << endl << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else
{
validInput = true;
}
}
cin.get();
return 0;
}
float Addition (float firstNumber, float secondNumber)
{
return firstNumber+secondNumber;
}
float Subtraction (float firstNumber, float secondNumber)
{
return firstNumber-secondNumber;
}
float Multiplication (float firstNumber, float secondNumber)
{
return firstNumber*secondNumber;
}
float Division (float firstNumber, float secondNumber)
{
return firstNumber/secondNumber;
}
Here's a suggestion how your final program could look like. Of course there are still many things you could improve! (Just for example: Using classes and OO code)
#include "stdafx.h" // inconvenient unportable windows stuff
#include <iostream> // cin and cout
#include <map> // the map
#include <limits> // numeric_limits
#include <string> // strings (obviously)
#include <cmath> // for NaN. ATTENTION: for gcc you have to compile with -lm
using namespace std;
int main(int argc, char* argv[])
{
int operatorSelection;
float firstNumber, secondNumber, result;
cout << "Welcome to OneOpCalc. ";
while (true)
{
cout << "Please select an operation by its number: ";
cin >> operatorSelection;
if (!cin.good() || operatorSelection > 4 || operatorSelection < 1)
{
cout << "Error: Invalid entry. Try again." << endl << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else
{
break;
}
}
do
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> firstNumber;
} while(!cin.good());
do
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> secondNumber;
} while(!cin.good());
switch(operatorSelection)
{
case 1:
result = firstNumber + secondNumber;
break;
case 2:
// don't devide by 0!
if(secondNumber == 0.0)
{
result = NAN;
}
else
{
result = firstNumber / secondNumber;
}
break;
case 3:
result = firstNumber * secondNumber;
break;
case 4:
result = firstNumber - secondNumber;
break;
default:
cout << "I'm sorry, something went terribly wrong";
return -1;
}
cout << "Your result is: " << result;
cin.ignore();
cin.get();
return 0;
}
Generally I can recommend to you this link, especially the tutorial section. Also, feel free to google for more tutorials and try out the examples.
Another hint: If you don't want to use stdafx.h, then disable precompiled headers in the project properties. Have a look at this and this.
In your particular case ,it would be better to use a map of pointers to functions:
map<int,float (*)(float, float)> Operations;
Operations.insert(pair<int,float (*)(float, float)>(1, Addition));
Operations.insert(pair<int,float (*)(float, float)>(2, Division ));
Operations.insert(pair<int,float (*)(float, float)>(3, Multiplication));
Operations.insert(pair<int,float (*)(float, float)>(4, Subtraction));
This way you can simply call functions like
Operations[operatorSelection](0,1);
P.S. there are few typos in your code - should be float result = instead of result, maybe other...
In terms of efficiency though, a simple switch() statement would probably be the most efficient...