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();
}
Related
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);
}
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);
}
Update 1: I need help with this the second part of this. I am asking the user to input numbers and to stop by using a zero. But then I want to display that code back. This is how far I got because when I want to display it it gives me different numbers. I'm ignoring user errors assuming when they input the first time it will be correct. But I do want them to input negative numbers.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
float data;
int count=0;
int*arr=new int[count];
//get amount of numbers inputted
cout<<"Please enter floating point data.\n";
cout<<"After the last number has been entered press 0 (zero) \n";
cin>>data;
for (; data != 0 ; ++count)
{
cin>>data;
}
cout<<count<<endl;
cout<<endl;
//display back data
cout<<"The numbers enterd are: "<<endl;
for(int i=0; i<count; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;
system ("pause");
return 0;
}
**Update 2:**This code is part of a bigger project I'm working on. My professor is never going to see the code he just cares that it is working. The design of my code is not a priority in this case. Also I have never used std::vector before so I needed another way to do it. But this is what I did and it worked fine. I also commented off delete []arr because my code wouldn't run properly if I didn't do that.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double data;
int count=0;
double *arr =new double[count];
//get data
cout<<"Please enter floating point data."<<endl;
cout<<"After the last number has been entered press 0 (zero)"<<endl;
do
{
cin>>arr[count];
data = arr[count];
count++;
}while(data != 0);
//display back data
cout<<"The numbers entered are: "<<endl;
for(int i=0; i<(count-1); i++)
{
cout<<arr[i]<<endl;
}
//delete []arr;
system ("pause");
return 0;
}
The given example code,
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
float data;
int count=0;
int*arr=new int[count];
//get amount of numbers inputted
cout<<"Please enter floating point data.\n";
cout<<"After the last number has been entered press 0 (zero) \n";
cin>>data;
for (; data != 0 ; ++count)
{
cin>>data;
}
cout<<count<<endl;
cout<<endl;
//display back data
cout<<"The numbers enterd are: "<<endl;
for(int i=0; i<count; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;
system ("pause");
return 0;
}
… has many issues:
Coding: using float for no reason.
The default floating point type in C and C++ is double. E.g. the literal 3.14 is of type double, and any float value is promoted to double when passed to variadic C function. Only use float where a requirement is imposed by the context, e.g. a C API, or storing a zillion values in limited memory.
Coding: using a raw array and a new-expression.
The task is trivial when using std::vector. It's not a good idea to reinvent the wheel again and again. An exercise that requires you to reinvent std::vector or its most basic features should be very clear about that aspect: this isn't, so presumably reinvention is not required or what it's about.
Design: signalling end-of-input via special value.
That value can't be inputted.
Coding: an input loop that doesn't store the numbers.
Each number is stored in the same variable as the previous number, erasing the previous number. Store the numbers in a std::vector. E.g. you can use the push_back method.
Coding: inconsistent convention for newline on output.
Either use endl, or "\n", as default. Don't mix them randomly. Consistency is very important because someone reading the code, who assumes a competent programmer, must treat every departure from the established defaults as being due to some reason. When there is no reason this wastes time and effort.
Tool usage: the system( "pause" ) is silly, counter-productive & non-portable.
In Visual Studio, which it appears you're using, just run the program via Ctrl+F5. Or place a breakpoint on the last right brace of main, and run the program in the debugger via F5.
Coding: the return 0; is superfluous.
main is the only function that has a default return value. It has that in both C and C++. The default, 0 for success, is there to be used.
Example code with the above points, plus some, fixed.
This code is for C++11 or later so it won't compile directly with Visual C++ 2010.
I leave it as an exercise for you to translate it to C++03, which is what your current compiler can handle. Do consider upgrading. It's a free tool.
#include <iostream>
#include <iomanip> // std::setw
#include <string> // std::(string, stod)
#include <vector> // std::vector
using namespace std;
using Half_float = float; // Most often a silly choice.
using Float = double; // Default in C++.
using Extended_float = long double; // Same as double in Visual C++.
auto read_line()
-> string
{ string line; getline( cin, line ); return line; }
auto main() -> int
{
cout << "Please enter floating point numbers like " << 3.15 << ", one per line.\n";
cout << "After the last number just press return again (i.e. a blank line).\n";
vector<Float> numbers;
for( ;; )
{
cout << "#" << numbers.size() + 1 << "? ";
string const line = read_line();
if( line.empty() )
{
break;
}
numbers.push_back( stod( line ) ); // Here you CAN do input validation.
}
cout << numbers.size() << " numbers entered.\n";
cout << "\n";
cout << "The numbers entered were: \n";
for( int i = 0; i < int( numbers.size() ); ++i )
{
cout << setw( 3 ) << i << ": " << numbers[i] << "\n";
}
}
If you have C++ 11 or above, use auto
replace
for(int i=0; i<count; i++)
{
cout<<arr[i]<<endl;
}
with
for(auto v: arr){
cout << v << endl;
}
Please remember, you'll need compiler supporting C++11 to use auto.
If C++ < 11, Use std::for_each
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void print(float v){
cout << v << endl;
}
int main ()
{
float data;
int count=0;
std::vector<float> arr;
//get amount of numbers inputted
cout<<"Please enter floating point data.\n";
cout<<"After the last number has been entered press 0 (zero) \n";
while(cin>> data && data != 0)
{
arr.push_back(data);
++count;
}
cout<<count<<endl;
cout<<endl;
//display back data
cout<<"The numbers enterd are: "<<endl;
std:for_each(arr.begin(), arr.end(), print);
cout<<endl;
system ("pause");
return 0;
}
The code will access out-of-bounds of arr, which has zero elements, unless you enter 0 for the first prompt.
You didn't assign what you read to "elements or arr" (actually there will be no elements in arr) at all.
There will be no reason why you should use array of int to store float data.
You should use std::vector, which works as variable-size array.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main ()
{
float data;
int count=0;
vector<float> arr;
//get amount of numbers inputted
cout<<"Please enter floating point data.\n";
cout<<"After the last number has been entered press 0 (zero) \n";
while(cin >> data && data != 0)
{
arr.push_back(data);
}
count = arr.size();
cout<<count<<endl;
cout<<endl;
//display back data
cout<<"The numbers enterd are: "<<endl;
for(int i=0; i<count; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;
return 0;
}
First off, this is for a homework assignment, so I'd appreciate help and guidance rather than just the answer in code.
The purpose of the code should be for a user to input a number and a width.
If the width is longer than the number, the number will be printed out with zeros in front of the number. For example 43 3 would give 043.
If the width isn't longer just the number would be printed: 433 2 would be 433.
I think I have to get the count of characters in the number and compare it to the count of characters in the width (if-else statement).
Then, if the number of characters in the number is more, print out the number. Else, print out the width.
I think I get the number of zeros by subtracting the length of the number from the length of the width. Then use that to set the number of zeros. Like I said this is homework and would rather learn than be given the answer.
If anyone can help, it'll be appreciated.
#include <iostream>;
#include <string>;
using namespace std;
string format(int number, int width) {
int count = 0;
if (number > width)// This if-else is incomplete
return ;
else
}
int main()
{
cout << "Enter a number: ";
string n;
cin >> n;
cout << "Enter the number's width: ";
string w;
cin >> w;
format(n, w);
}
no need to checking string or other things write these code C++ will do it for you automatically.
#include <conio.h>
#include <iostream>
using std::cout;
using std::cin;
#include <string>;
using std::string;
#include <iomanip>
using std::setw;
void format(int number, int width)
{
cout.fill('0');
cout << setw(width) << number;
}
int main()
{
cout << "Enter a number: ";
int n;
cin >> n;
cout << "Enter the number's width: ";
int w;
cin >> w;
format(n, w);
_getch();
return 0;
}
I'm very confused when it comes to arrays and I've got a mini-project on using them but i'm stuck at a certain part in my program and I don't know what to do next, can anyone help?
the question is:
"Write a C++ program that reads 5 integers from the screen (provided by the user) and determines the largest integer. You MUST use an array to store the 5 integers.
The following shows a sample output of the program.
Enter 5 integers: 15 36 -8 92 56
The largest integer is 92 "
what i've got so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int userIntegers[5];
cout<<"Enter 5 integers: ";
cin>>userIntegers[0];
//system("pause");
return 0;
}
Here is the thing you have to do. You need to use a FOR or WHILE loop to get the certain number of user input and store them in array.
int userIntegers[5];
int largest = 0;
cout<<"Enter 5 integers: ";
for (int i=0; i<5; i++) //Use for loop upto how many numbers you need to get as input.
{
cin>>userIntegers[i];//get the input from user and store it in array at the index
/*If the input is the larger than prev largest or For special case to handle if all the values entered is less than zero.*/
if(largest < userIntegers[i] || largest == 0)
{
largest = userIntegers[i];//Assign the largest number to the variable.
}
}
cout<<"Largest Integer is: "<<largest;
or you can do more easily (using isstringstrem and INT_MIN):
int maxnumber = INT_MIN; // for being sure to have at lest one number above
int number;
string s;
cout<<"Enter 5 integers: ";
cin >> s;
std::istringstream steam( s );
while(steam >> number) {
if (number > maxnumber) {
maxnumber = number;
}
}
EDIT:
If you need an array #Sridhar seem have your answer (but think about using INT_MIN http://www.cplusplus.com/reference/climits/)