i am trying to find the average but this could not resolve. This code showing me 'runtime erorr' kindly help me my code is here:
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
I do not understand what is 'n' standing for. I found some problems with your script. First of all u should define the 'n'. Secondly, it's better not to use the loop for checking.
Thirdly, i suggest u to use this code":
int n;
cin>>n;
if(n>100 && n<0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
Related
Note: I am a beginner in C++, so please bear with me if there are any serious programming errors that can be fixed easily.
Edit: Options 3 and 4 work perfectly fine without any errors. However, Option 2 has a serious looping problem where 'Error! Number should be in range of (1 to 100)' and 'Enter the number again:' loop continuously when you input any key. Will change the code to show the code for Option 2 and remove Option 3 and Option 4's code.
I created a math program that can calculate numbers, calculate fractions, among other features I added. I added a continue button on some programs (Option 2) that when you enter 'Y' on your keyboard, it should loop the program until the user types a different key to signify that the program should stop. However, the continue button seems not to work. When I press any other key, the program still loops and I have to stop the program so it cannot loop.
#include <<iostream>>
#include <<cmath>>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n":
std::cout << "Option 1: Calculator" << std::endl "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
{
printf("\n Chose average calculator.");
char d;
int n, i;
float num[100],
sum=0.0,
average;
anon:
{
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
}
cout << "\nDo you want to continue? "; cin >> n;
if (n== 'Y', "Yes")
goto anon;
system("PAUSE");
return 0;
break;
}
I'd appreciate any help on this issue or a detailed explanation since this is very confusing for me.
Your code is fine but you just have some typos in these lines.
cout << "\nDo you want to continue? ";
cin >> n;
/*Here => */ if (n== 'Y', "Yes")
fix it to if(n == 'Y'), also you have unintentionally used n instead of the char d that you have defined to use as a check.
So your code should be
cout << "\nDo you want to continue? ";
cin >> d;
if (d == 'Y') { .... }
And for completion, avoid goto whenever you can. You can use a while loop instead of the assembly-like goto.
This is your code but with a while loop instead of goto
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n";
std::cout << "Option 1: Calculator" << std::endl << "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
printf("\n Chose average calculator.");
char d = 'Y';
int n, i;
float num[100],
sum=0.0,
average;
while (d == 'Y'){
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
cout << "\nDo you want to continue? ";
cin >> d;
}
break;
}
}
I currently have a function set up that asks the user for an int, obtains that int, and then checks to make sure that the input meets a certain specification. In this case, its expected that the input will be an integer between -10 and 100. As of now, if I input any string of letters E.G. "gfUIWYDUF", the function returns a 0. Why is this happening and how do I fix it?
int readUserInput() {
cout << "What is the answer?: " << endl;
int answer;
do {
cin >> answer;
if (!cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
}
} while(!cin || answer < -10 || answer > 100);
return answer;
}
If you play with the input values you will find that cin >> scans from left to right until it finds any non-numeric value. It then evaluates the numbers it did find.
For example, putting:
57gh5
Returns 57
If you enter only numeric characters, you have a score of 0.
If you cin >> string instead, then you will be able to parse/validate the string and convert a valid number into an int
The problem is that your validation loop for this type of input depends on the error state of std::cin. However, you clear that error state before the loop checks for it.
The simplest way to fix this is to move your reading from std::cin to after the clear() like this:
// Read first
cin >> answer;
do {
if (!cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
cin >> answer;
}
} while(!cin || answer < -10 || answer > 100);
Though, I think I prefer using a regular while loop instead myself:
cin >> answer;
while(!cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
cin >> answer;
}
This feels cleaner to me, but that's just me. Both loops will work.
0 is returned as the initial value of answer
You may use cin.fail() to check if the input is valid.
int readUserInput() {
cout << "What is the answer?: " << endl;
int answer;
do {
cin >> answer;
if (cin.fail() || !cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
}
} while(cin.fail() || !cin || answer < -10 || answer > 100);
return answer;
}
I'm trying to make a validation loop in C++ that checks the user's input until they enter a number between 0 and 100 and however my loop only checks the first condition. Any guidance is appreciated!
#include <iostream>
using namespace std;
int main()
{
const int max_num = 100;
const int min_num = 0;
int num;
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
do {
if (!(cin >> num))
{
cout << "ERROR:The value provided was not a number" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
else if (num<min_num || num>max_num)
{
cout << "ERROR: value out of range" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
} while (!(cin >> num) || (num<min_num || num>max_num));
return 0;
}
Add lots of logging to your code so that you know what it's doing. This will help you find the problem. For example, instead of:
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
Try:
cout << "Enter a number between 0 and 100" << endl;
cerr << "About to read into num outside the loop" << endl;
cin >> num;
cerr << "Read into num outside the loop, got: " << num << endl;
And so on, throughout your code. This should give you enough information to find the bug. Alternatively, use a debugger with a single step function to accomplish the same thing.
Check that in the part of while:
instead of
while (!(cin >> num) || (num<min_num || num>max_num));
this:
while (!cin || (num<min_num || num>max_num));
the same for the upper if
cin >> num means putting user input to the variable num . So you are trying to take user inputs 2 times in the loop. Maybe the check condition: (num == (int)num)will solve your problem. It will try to verify the number you have stored in num is really of the type int
I'm trying to write a program which calculates prime numbers and I have issues with a do-while-loop I am using.
Code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
unsigned long int lower_limit;
unsigned long int upper_limit;
cout << "\n" << "Program calculates prime numbers in a given range between 2 and 4.294.967.295.";
cout << "\n" << "Input range in which prime numbers are to be calculated... ";
do
{
cout << "\n\n" << "Lower Limit:\t"; cin >> lower_limit;
cout << "\n" << "Upper Limit:\t"; cin >> upper_limit;
if(lower_limit >= upper_limit)
{
cout << "\nInvalid Input: Value of Upper Limit has to be bigger than value of Lower Limit.";
cout << "\nSelect new numbers.";
}
if(!(cin >> lower_limit) || !(cin >> upper_limit))
{
cout << "\nInvalid Input: Values of Lower Limit and Upper Limit have to be integers.";
cout << "\nSelect new numbers.";
}
}while(lower_limit >= upper_limit || !(cin >> lower_limit) || !(cin >> upper_limit));
return(0);
}
If I input values to trigger Lower Limit >= Upper Limit it triggers the first error properly, but doesn't repeat the do-while-loop afterwards and doesn't close the program (return(0)) either... So the program is not repeating the do-while-loop, neither is the program exiting it. I really have no clue what it is actually doing there.
If I input values to trigger !(cin >> lower_limit) || !(cin >> upper_limit) ("adfd" or the like) the whole program just goes mental and rapidly repeats the do-while-loop, even ignoring the cin >> lower_limit; and cin >> upper_limit; statements.
Does anybody have an idea that can help me out?
Cheers!
One point is that if you get invalid input, you need to clear the error state by:
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Your loop should be changed to something like:
do
{
while ( !(cin >> lower_limit >> upper_limit) ) {
cout << "Invalid input, Please re-enter\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if(lower_limit >= upper_limit)
{
cout << "\nInvalid Input: Value of Upper Limit has to be bigger than value of Lower Limit.";
cout << "\nSelect new numbers.";
}
} while(lower_limit >= upper_limit);
This program should check if entered number is integer. It works fine with strings but not with doubles.
int test;
cout << "Enter the number:" << endl;
while(true) {
cin >> test;
if (!cin || test < 0) {
cout << "Wrong input, enter the number again:" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
test is int. istream >> operator is just dynamic casting to int and, then, you're losing decimal part.
Yo can just define test as float and cast it to int when needed.
Edit: Answering you last edit (I didn't refresh so I missed this part), what is happening is that, without the gotoyou're looping twice:
You enter 1.5
test is 1 and you don't enter if, so cin is not cleaned up.
loops again and cin immediately returns.
test is 0 so enters if statement and complains.
Hope this helps
Try this:
int test;
cout << "Enter the number:" << endl;
while ( true )
{
cin >> test;
if (!(test < 0 || !cin))
break;
}
cout << "Your chosen number is: " << test << endl;
Is that what you want?