why is my last else condition not executing correctly - c++

why is it when I input anything other than int I get 0 is an even number, the plan was if the user enters something that's not an integer it should output invalid input
cout << "Enter an integer: ";
cin >> input;
if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else if(input % 2 != 0) {
cout << input << " is an odd "
"number" << endl;
}else {
cout << "Invalid input!" << endl;
}

cin >> input is an operation that can fail, and if it fails the input variable does not contain a useful value. You can check whether it succeeded by converting cin to bool:
cin >> input;
if (!cin) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...
Or, since cin >> input returns the cin object again, this is equivalent:
if (!(cin >> input)) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...

Here's the code that works thanks to jtbandes
Exercise - Write a program to check whether a given number is ODD or Even
cout << "Even/Odd Program" << endl;
int input;
cout << "Enter an integer: ";
cin >> input;
if (!(cin >> input)) {
cout << "Invalid input!" << endl;
} else if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else
cout << input << " is an odd "
"number" << endl;
return 0;
}

Related

Stuck on a loop

I already posted this question, but none of the responses were correct once I implemented the suggestions I was given. Here is what I need to happen.
Would you like to process all the records in the file? (y/n) w
Error - Please enter either y or n.
Would you like to process all the records in the file? (y/n) n
Enter number of records to process: two
XXXXXXXXXX Error-non numeric or negative value, try again
Enter number of records to process: -10
XXXXXXXXXX Error-non numeric or negative value, try again
Enter number of records to process: 0
XXXXXXXXXX Error-non numeric or negative value, try again
Enter number of records to process: 10
Maximum requested record count of 10 reached
Here is what I have. I don't know what I am doing wrong.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? "
<< "(y/n) ";
cin >> a;
if (a == 'y')
{
cout << "Processed all records successfuly" << endl;
}
do
{
if (a == 'n')
{
cout << "Enter number of records to process: ";
cin >> ProcessAmount;
if (ProcessAmount <= 0 or cin.fail())
{
cout << "" << endl;
cout << "XXXXXXXXX Error-non numeric or negative value";
cout << "" << endl;
cin >> ProcessAmount;
}
else if (ProcessAmount >= 0 or (!(cin.fail())))
;
{
cout << "Maximum requested record count of " << ProcessAmount;
cout << " reached" << endl;
break;
}
}
else
(cin.fail());
{
cin.clear();
cin.ignore(40, '\n');
cout << "Please try again" << endl;
cout << "Would you like to process all the records in the file? "
<< "(y/n) ";
cin >> a;
}
} while (a == 'n');
}
First of all or is something I didn't know worked in C++, but in my gcc compiler it works fine, so thank you for that, I still replaced it with || in my answer, though.
Apart from that there are some issues with the sequence of events in your do - while cycle, try the code below.
Live sample here
do {
if (a == 'y') {
cout << "Processed all records successfuly" << endl;
break;
}
if (a == 'n') {
cout << "Enter number of records to process: ";
cin >> ProcessAmount;
if (ProcessAmount <= 0 || cin.fail()) {
cout << "XXXXXXXXX Error-non numeric or negative value";
cout << "" << endl;
}
else {
cout << "Maximum requested record count of " << ProcessAmount;
cout << " reached" << endl;
break;
}
cin.clear();
cin.ignore(40, '\n');
continue;
}
cout << "Please try again" << endl;
cout << "Would you like to process all the records in the file? "
<< "(y/n) ";
cin >> a;
} while (a != 'y');
First of all, the value of a must be validated, with something like:
cout << "Would you like to process all the records in the file? "
<< "(y/n) ";
cin >> a;
//validating a
while (a != 'n' && a != 'y'){
cout << "Error - Please enter either y or n." << endl;
cout << "Would you like to process all the records in the file? "
<< "(y/n) ";
cin >> a;
}
//...do things if a='n'
//...do thing if a='y'
then you should stop worrying about a, then you can do things if a = n or if a = y

cin >> int given a string assigns int to 0

The issue that I'm having is that if you input any string the cin will assign the int to 0. An interesting finding is that if you later take cin to a string you get the entire string you put in for the int. cin.fail() always returns true for some reason, even with cin.ignore(), etc and if( cin >> startingPosition ) also always returns true. So, how do I get it to catch an even recognize that it's a string and not an int? As in, how do I have it loop again if it is a string?
int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
cin >> startingPosition;
while (startingPosition >= WIDTH || startingPosition < 0) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
cin >> startingPosition;
cout << startingPosition << endl;
}
return startingPosition;
}
you must save result from cin
isNumber = (cin >> startPosition);
the whole code will look like
int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
bool isNumber = (cin >> startingPosition);
while(isNumber && (startingPosition >= WIDTH || startingPosition < 0)) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
isNumber = (cin >> startingPosition);
cout << startingPosition << endl;
}
return startingPosition;
}

issue with program loops and if statements

I'm writing a program that tells a user when they enter a negative or positive and even or odd number
then the program ask a question, " Would you like to enter another number? y(es) or n(o)
I need to account for the user entering in something else besides 'y' and 'n'
and I need to account for if the user does not enter an integer. Last if the user selects yes, the program will need to go through the loop process of determining if they enter an integer and if its (positive or negative and odd or even)
int value;
char choice;
cout << "Please enter a number" << endl;
cin >> value;
while (!(cin >> value)) {
cin.clear();
cin.ignore(999, '\n');
cout << "Invalid data type! Please enter 'value' again" << endl;
}
if (value > 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is positive" << endl;
}
else if (value < 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is negative" << endl;
}
else if (value > 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is postive" << endl;
}
else if (value < 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is negative" << endl;
}
cout << "Would you like to try another number? Say y(es) or n(o)" << endl;
cin >> choice;
while (choice != 'y' &&choice != 'n') {
cin.clear();
cin.ignore(999, '\n');
cout << "Invalid response! Please enter 'choice' again" << endl;
}
do {
if (choice == 'y') {
cout << "Please enter a number" << endl;
cin >> value;
if (!(cin >> value)) {
cin.clear();
cin.ignore(999, '\n');
cout << "Invalid data type! Please enter 'value' again" << endl;
if (value > 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is positive" << endl;
}
else if (value < 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is negative" << endl;
}
else if (value > 0 && value % 2 != 0) {
cout << value << " is odd" << endl;
cout << value << " is postive" << endl;
}
else if (value < 0 && value % 2 == 0) {
cout << value << " is even" << endl;
cout << value << " is negative" << endl;
}
cout << "Would you like to try another number? Say y(es) or n(o)" << endl;
cin >> choice;
}
}
} while (choice == 'n');
cout << "Thank you for using my program. Goodbye!" << endl;
return 0;
}
It would take nested do-while loops to check all your conditions.
Here I am using cin.fail(). cin.fail() detects whether the value entered fits the value defined in the variable.
int value;
char choice;
do{
cout << "Please enter a number" << endl;
cin >> value;
if(cin.fail()) // check if input is int
{
cout<<"Not an int";
choice = 'y';
}
else
{
if (value > 0 && value % 2 == 0)
{
cout << value << " is even" << endl;
cout << value << " is positive" << endl;
}
else if (value < 0 && value % 2 != 0)
{
cout << value << " is odd" << endl;
cout << value << " is negative" << endl;
}
else if (value > 0 && value % 2 != 0)
{
cout << value << " is odd" << endl;
cout << value << " is postive" << endl;
}
else if (value < 0 && value % 2 == 0)
{
cout << value << " is even" << endl;
cout << value << " is negative" << endl;
}
do{
cout << "Would you like to try another number? Say y(es) or n(o)" << endl;
cin >> choice;
}while(choice != 'y' || choice != 'n');
}
}while (choice == 'n');
Also you should read this: Checking input value is an integer

How can I avoid bad input from a user?

I am a very newbie programmer, so I don't really know much about writing code to protect the application.. Basically, I created a basicMath.h file and created a do while loop to make a very basic console calculator (only two floats are passed through the functions). I use a series of if and else if statements to determine what the users wants to do. (1.add, 2.subtract, 3.multiply, 4.divide) I used a else { cout << "invalid input" << endl;} to protect against any other values, but then I tried to actually write a letter, and the program entered a infinite loop. Is there anyway to protect against users who accidentally hit a character instead of a number?
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
One way would be to use exception handling, but as a newbie you're probably far from learning that.
Instead use the cin.fail() which returns 1 after a bad or unexpected input. Note that you need to clear the "bad" status using cin.clear().
A simple way would be to implement a function:
int GetNumber ()
{
int n;
cin >> n;
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Not a valid number. Please reenter: ";
cin >> n;
}
return n;
}
Now in your main function wherever you are taking input, just call GetNumber and store the returned value in your variable. For example, instead of cin >> numOne;, do numOne = GetNumber();
When you input to cin, it is expecting a specific type, such as an integer. If it receives something that it does not expect, such as a letter, it sets a bad flag.
You can usually catch that by looking for fail, and if you find it, flush your input as well as the bad bit (using clear), and try again.
Read a whole line of text first, then convert the line of text to a number and handle any errors in the string-to-number conversion.
Reading a whole line of text from std::cin is done with the std::getline function (not to be confused with the stream's member function):
std::string line;
std::getline(std::cin, line);
if (!std::cin) {
// some catastrophic failure
}
String-to-number conversion is done with std::istringstream (pre-C++11) or with std::stoi (C++11). Here is the pre-C++11 version:
std::istringstream is(line);
int number = 0;
is >> number;
if (!is) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
} else if (!is.eof()) {
// line is a number, but ends with a non-number, e.g. "123abc",
// whether that's an error depends on your requirements
} else {
// number is OK
}
And here the C++11 version:
try {
std::cout << std::stoi(line) << "\n";
} catch (std::exception const &exc) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
std::cout << exc.what() << "\n";
}

Input errors in c++ program

when press "1" to start the game a error message comes up first instead of playing the game and then I have to enter "1" 3 times before the game starts and also the quit game option only works when you select "2" first if its not selected first it just comes up as a error message I cant see why it does this can anyone help me please ?
#include "Questions.h"
#include <iostream>
using namespace std;
const int MAXITEMS = 10;
int main ()
{
string question[MAXITEMS] = {"How man cards in a suit",
"How_many_suits_are_there_in_a_standard_pack_of_card",
"How_many_kings_are_in_a_standard_pack_of_cards"};
string answers[MAXITEMS] = {"4", "5", "6"};
int userInput = 0;
int tries = 0;
bool isGameOver = false;
cout << "select 1 to start game" << endl; //gives option to start and quit game
cout << "select 2 to quit game" << endl;
cin >> userInput;
if (userInput == 2)
{
isGameOver = true;
return 0;
};
// when game starts gives option to select question and shows all questions
do
{
if (userInput != 1||2)
{
cout << " Your input is not valid! please try again:" << endl;
// try switch cases for the different outcomes
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
cin >> userInput;
while (!(cin >> userInput))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n'); // discard the row
cout << "Your input is not valid! please try again: ";
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
}
cout << userInput << endl;
}
// reprisent all characters as number to stop while roblem
if(userInput == 1)
{
do
{
cout << "select question" << endl;
for(int i = 0; i != MAXITEMS; i++)
{
cout << i << " " << question[i] << endl;
}
int selectQestion;
cin >> selectQestion;
if(selectQestion == 0||1||2 && tries != 2)
{
cout << "Enter your answer" << endl;
string userAnswer;
cin >> userAnswer;
while (!(cin >> userAnswer))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n');
// discard the row
cout << "Your input is not valid!
please try again: ";
}
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else{
cout << "incorrect try again" << endl;
tries++;
cin >> userAnswer;
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else
cout << "Incorrect" << endl;
}
}
if (selectQestion == 0 ||1 ||2 && tries == 2)
{
cout << "you can no longer answer this question" << endl;
cout << "try another question" << endl;
}
}
while(userInput == 1);
}
}
while(isGameOver == false);
}
// add stuct or class to handle questions,
if (userInput != 1||2) doesn't do what you think. With the proper paretheses inserted, it is
if ((userInput != 1) || 2)
and 2 is nonzero, hence the condition is always true.
You want
if (userInput != 1 && userInput != 2)
The problem lies here:
if (UserInput!=1||2)
In this line, there are two conditions:
UserInput!=1 , 2
Here , whether user input is 1/2, the second condition 2 is always evaluated as true, which runs the if block
So change it to
if (UserInput!=1 && UserInput!=2)