I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;
Related
int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;
This question already has answers here:
How to check if the input number integer not float?
(3 answers)
How to check if the input is a valid integer without any other chars?
(7 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I am new to c++ - and I am having trouble to validate user that the input must be a integer, and I just want the basic - simpler way, for me to understand. (Just basic way) to validate the input of the user How can I make it to work prior to my code below. Thank you for you're help and you're time. For example: if I get prompt to enter positive number and Input the letter x that means it will show "Invalid entry".. thank you!
Here is my code:
Updated
if (cin >> x && x < 0) {
} else {
cout << "Invalid entry, Try again." << endl;
cin.clear();
while (cin.get() != '\n');
}
#include <iostream>
#include <fstream> // for file stream.
using namespace std;
int main() {
// Variables
int x, reversedNumber, remainder;
// Creating String variables and setting them to empty string.
string even = "", odd = "";
// Creating a file.
ofstream out;
out.open("outDataFile.txt");
// creating a character variable
// for the user input if they want to use the program again.
char ch;
do {
// Even number.
even = "";
// Odd number.
odd = "";
// Reversed number
reversedNumber = 0;
// Prompt the user to enter a positive integer.
cout << "\nEnter a positive integer and press <Enter> ";
// Validate user input.
while (cin >> x || x < 1) {
// Clear out the cin results.
cin.clear();
// Display user that it is not a positive integer.
cout << "Invalid entry, Try again. ";
}
// Display Results to the screen
cout << "the original number is " << x << "\n";
// Display results in the text file.
out << "the original number is " << x << "\n";
// Display number reversed.
cout << "the number reversed ";
// Display number reversed in text file.
out << "the number reversed ";
//Reversing the integer.
while (x != 0) {
remainder = x % 10;
reversedNumber = reversedNumber * 10 + remainder;
// Display on screen
cout << remainder << " ";
// Display in text file.
out << remainder << " ";
x /= 10;
}
// Display the results on screen and in the text file.
cout << "\n";
out << "\n";
// Reading the reverse numbers result.
while (reversedNumber != 0) {
remainder = reversedNumber % 10;
// Checking if the number is even or odd.
if (remainder % 2 == 0) {
// even = even * 10 + remainder;
} else {
// odd = odd * 10 + remainder;
}
reversedNumber /= 10;
}
//Displaying the even numbers.
if (even != "") {
cout << "the even digits are " << even << "\n";
out << "the even digits are " << even << "\n";
}
// If it is not even then display..
else {
cout << "There are no even digits \n";
out << "There are no even digits \n";
}
//Display the odd results.
if (odd != "") {
cout << "the odd digits are " << odd << "\n";
out << "the odd digits are " << odd << "\n";
}
// If its not odd then display.
else {
cout << "There are no odd digits \n";
out << "There are no odd digits \n";
}
// just a divider to divide the results inside text file.
out << "----------------- \n";
// Prompt the user if they want to use the program again.
cout << "\nDo you like to continue/repeat? (Y/N):";
// get the input from user.
cin >> ch;
if ((ch == 'Y') || (ch == 'y')) {
} else {
cout << "\nGoodbye!" << endl;
}
} while (ch == 'y' || ch == 'Y');
// close the text file.
out.close();
return 0;
}
You could read a string from cin and check each character to make sure that when passed to isdigit() it returns true.
std::string x;
std::cin >> x;
for(char c : x){ //for each char c in string x
if(!isdigit(c)) //Invalid
}
Im trying to get the program to only accept x as an integer then ask for another integer, y. However when i enter a floating point into x it takes the decimal part of the input and makes that the y value. i am unsure of my mistake here.
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int getInt()
{
int x = 0;
while (!(cin >> x))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please input a proper 'whole' number: " << endl;
}
return (x);
}
int toobig()
{
cout << "Your number is too large, please enter something smaller: " << endl;
int x = getInt();
return (x);
}
int toosmall()
{
cout << "your number is negative, please enter a positive number: " << endl;
int x = getInt();
return (x);
}
int main()
{
cout << "your number please:-" << endl;
int x = getInt();
if (x>100000)
{
toobig();
}
else if (x<0)
{
toosmall();
}
int y = 0;
cout << "enter y " << endl;
cin >> y;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
system("PAUSE");
return 0;
}
Most conversions to int stop as soon as they find something that can't be part of an int and only a few conversion functions tell you if they stop before parsing the whole string.
Let's use one of those few, shall we?
int getInt()
{
for ( ; ; ) // loop until user provides something we can use.
// This is dangerous. You probably want to give up after a while.
{
std::string input; // read in as string
if (std::cin >> input)
{
char * endp; // will be updated with pointer to where conversion stopped
errno = 0;
// convert string to int
long rval = std::strtol (input.c_str(), &endp, 10);
if (*endp == '\0') // check whole string was read
{
if (errno != ERANGE) // check converted number did not overflow long
{
if (rval >= std::numeric_limits<int>::min() &&
rval <= std::numeric_limits<int>::max())
// check converted number did not overflow int
// you could replace this min and max with your own passed-in
// min and max values if you want
{
return rval; // return the known-to-be-good int
}
}
}
}
else
{ // note: usually when cin fails to read a string, it's over.
// This is actually a good time to throw an exception because this
// just shouldn't happen.
std::cin.clear(); // but for now we'll just clear the error and
// probably enter an infinite loop of failure
}
// failed for any reason. Blow off all user input and re-prompt
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please input a proper 'whole' number: " << std::endl;
}
return 0; // to satisfy compiler because a non-void function must always return.
// Never reached because of infinite for loop.
}
since every console input on C++ is treated as a string, then under your getInt() method I would do the following:
int GetInt(istream &stream)
{
char obtainChar; //read a character from input
int x;
stream >> x;
while(stream.fail() || (stream.peek() != '\r' && stream.peek() != '\n'))
{
stream.clear(); //clear the fail state of stream
obtainChar = stream.get(); //read a character from input
while(obtainChar != '\n' && obtainChar != EOF) //while gotten char is not a return key or EOF
obtainChar = stream.get(); //read a character from input iterate up to '\n' or EOF
//displays an error message if there was a bad input (e.g. decimal value)
cerr << endl << "Please input a proper 'whole' number: " << endl;
cout << endl << "Please re-enter x: "; //re-prompt to re-enter a value
x = GetInt(stream); //Try again by calling the function again (recursion)
}
return x; //will return after the user enters ONLY if an integer was inputted
}
the first while is basically saying, if the stream (console input) does fails or the next stream char (.peek()) is not a \r or a \n the clear the stream and get the first character.
while that char is not a \n and not End Of File (EOF) then obtain the next char, so on and so forth.
if a problem occurred then display a error message to the user and re-prompt the user for the value of x.
then call the same function to re-test the input (recursively), if all is well then return the value of x.
you can now call this function to evaluate the value of Y.
NOTE: istream is part of the iostream library is basically cin
NOTE: call the function like so:
int x;
cout << "your number please:-" << endl;
x = GetInt(cin);
I've created a program that allows the user to enter 10 grades. I've used a while loop to store grades in the array, but if the user only has 5 grades to input, he can type done to exit the program.
After the loop has finished, it will then calculate and display. the highest grade, lowest grade, and the average grade within the array
Unfortunately, when the user types done, the program will display the rest of the grade lines that were not entered.
Can you help me find out how to stop the while loop from displaying the rest of unentered grades of the loop?
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int grade[SIZE];
int count = 0;
int lowestGrade;
int highestGrade;
bool done = false;
cout << "This program is limited to entering up to 10 grades." << endl;
while ( grade[count] != done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
}
//LOWEST GRADE
lowestGrade = grade[0];
for (count = 0; count < SIZE; count++)
if (grade[count] < lowestGrade)
{
lowestGrade = grade[count];
}
//HIGHEST GRADE
highestGrade = grade[0];
for (count = 0; count < SIZE; count++)
{
if (grade[count] > highestGrade)
{
highestGrade = grade[count];
}
}
//AVERAGE GRADE
double total = 0;
double average;
for (int count = 0; count < SIZE; count++)
total += grade[count];
average = (total / SIZE);
cout << endl;
cout << "Your highest grade is: " << highestGrade << endl;
cout << "Your lowest grade is: " << lowestGrade << endl;
cout << "Your average grade is: " << average << endl;
system("pause");
return 0;
}
Here are two problems with your code.
First:
....
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
....
The code above will attepmpt to read word "done" into integer variable, producing 0. Not what you want to do!
Second:
...
for (count = 0; count < SIZE; count++)
...
Code above will try to iterate over all possible elements (SIZE). However, you might have enetered less than that! You need to use count calculated in the previous loop as your boundary (and of course, use a different name for control variable in the loop).
There are a couple of things to unpack here.
Basically, the input you are retrieving is a char * and the >> operator is casting that to an int to fit into your array of grades.
Next what you are checking with grade[count] != done is if the integer in "grade" at the id "count" is not equal to the bool false. This will always return true in this case.
For your use case what you want to be checking is if your input is equal to the char * "done"
This cannot be happening in the predicate of the while loop because your grade array stores only int.
Therefore the simplest solution to the problem in my opinion, is to check whether the input is equal to "done".
If it is you want to set the done boolean to true
Otherwise we can try to cast it to an int and store that in the grades array.
Here is the revised loop:
while (!done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string input = "";
cin >> input;
if (input == "done")
{
done = true;
}
else
{
grade[count] = stoi(input);
}
count++;
}
The following is somewhat outside the scope of the question, but an additionnal advantage to using stoi() is that it ignores input that is not a number, which will shield against someone entering invalid input like "potato". This is why I immediately cast the input into a string.
Use another variable to store the amount ofgrades the user entered. You also cannot store a string in your integer array:
std::string input = "";
while(count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
getline(cin, input);
if(input == "done")
break;
try
{
grade[count] = std::stoi(input);
count++;
}
catch(std::invalid_argument)
{
cout << "not a valid number\n";
}
}
int actualsize = count;
and then use this variable to abort your for loops:
for (int i = 0; i < actualsize; i++)
There are two simple ways to solve your problem:
You can read strings instead of integers and in case the read string is "done", break the loop, else, convert the read string to an integer, something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string temp;
cin >> temp;
if(temp == "done") {
break;
} else {
grade[count] = stoi(temp);
count++;
total_count = count;
}
}
// rest of the code
```
If you don't want to use strings, then, assuming grades will be non-negative, you can stop reading input when the user types a negative number, say "-1". So, you will need to do something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or -1 to quit: ";
int temp;
cin >> temp;
if(temp == -1) {
break;
} else {
grade[count] = temp;
count++;
total_count = count;
}
}
// rest of the code
```
Also, don't forget to replace SIZE by total_count in rest of the loops i.e. the ones computing 'LOWEST GRADE', 'HIGHEST GRADE' and 'AVERAGE GRADE'.
NOTE: You will have to do #include <string> at the top as well, if you use the first option.
I am trying to write a simple program in C++ that reads in an unspecified number of marks, then once the user inputs the character 'q', the program must calculate and display the average mark. However I am having some trouble. The approach I am taking is to save each value as a double, the I want to compare the double to the character 'q' and if they are the same character, end the loop, calculate and display the average.
However I think that the comparison between the char value 'q' and double value for the mark seem to be incomparable. This worked for me when I did the same using integer values for the mark but not doubles it seems. Any help would be appreciated.
Here is the code:
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
double mark;
cin >> mark;
if (mark != 'q')
{
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}
you'll need to change the mark variable to string, and then compare it to 'q', else try to parse is as a number.
otherwise this entire code, does not make a lot of sense, because 'q' in ASCII is 113, which I guess is a possible value
Typecast double to int and then compare, It must work because it compares ASCII value of character
Here is the code:
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
double mark;
cin >> mark;
if ((int)mark != 'q')
{
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}
you can not cast a double to char. You may need to use additional c++ library functions which convert string (char*) to double. There are different ways to do this.
Try this :
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
char userinput[8];
cin >> userinput;
std::stringstream ss;
double mark;
if (userinput[0] != 'q')
{
ss << userinput;
ss >> mark;
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "total : " << total << " count : " << counter << endl;
cout << "Average: " << average << endl;
return 0;
}
You are doing it wrong. If you try to cin a char into a double variable, the input char stays in the input buffer and the double variable remains the same. So this will end in an infinite loop.
If you really want the user to enter a char to end input, you need to take the whole input in a string variable. Check the string for q. If not present, use atof() to convert it to double.