How to use If statement with a boolean function in another class - c++

I have a class EverTrueHelper.cpp.
bool EverTrueHelper::getAndReturnUserEntry(string userEntry)
{
if (userEntry == "Q" || userEntry == "q")
{
return true;
}
else
{
return false;
}
return 0;
}
and I have these lines of code in my main function
cout << "Do you want to quit? Type 'Q' or 'q' else hit Enter" << endl;
cin >> userEntry;
if (getAndReturnUserEntry = true)
{
break;
}
else
{
continue;
}
I have an error on the "getAndReturnUserEntry" in my if statement. I can't quite figure out how to get around it.

You can call a method by using parentheses (()) and passing the argument(s) in them:
cin >> userEntry;
if (getAndReturnUserEntry(userEntry))
{
break;
}
else
{
continue;
}

You can try like follow:
cin >> userEntry;
EverTrueHelper my_helper;
if (my_helper.getAndReturnUserEntry(userEntry)) {
break;
}else{
continue;
}

You have two problem with your main function's if statement:
A single =, which means assignment, which is invalid in that case.
You have not invoked getAndReturnUserEntry, add () at the end to actually invoke the function. After that, a test for == true is not necessary either since it will work anyway.
cout << "Do you want to quit? Type 'Q' or 'q' else hit Enter" << endl;
cin >> userEntry;
if (getAndReturnUserEntry())
{
break;
}
// continue program...
Further more, I think a better quit checking function will be:
bool EverTrueHelper::getAndReturnUserEntry(string userEntry)
{
return (userEntry == "Q" || userEntry == "q");
}

bool EverTrueHelper::getAndReturnUserEntry(string userEntry) {
return ((userEntry == "Q" || userEntry == "q") ? true : false);
}
cout << "Do you want to quit? Type 'Q' or 'q' else hit Enter" << endl;
cin >> userEntry;
if (getAndReturnUserEntry(userEntry) == true)
; // break; doesn't make sense here
else
; // continue; doesn't make sense here

Related

How to check every character in string?

The program will ask user to input strand which has to be composed of only ABCD and if the input contains letter other than ABCD it must show error, otherwise it should output "ok!"
string strand1;
again:
cout << "Enter String 1:\n";
cin >> strand1;
for (int i = 0; i <= strand1.length(); i++)
{
if (strand1.at(i) != 'A'&&strand1.at(i) != 'B'&&strand1.at(i) != 'C'&&strand1.at(i) != 'D')
{
cout << "Invalid Input";
system("cls");
goto again;
}
else
{
i++;
}
}
cout << "ok";
_getch();
return 0;
Move the necessary checks to a function -- isValidInput.
Use hand coded logic to check whether the input is valid or use the standard library function std::find_if to do the same.
Use the function in a while loop in the main function.
bool isNotABCD(char c)
{
return !((c == 'A') || (c == 'B') || (c == 'C') || (c == 'D'));
}
bool isValidInput(std::string const& str)
{
return (std::find_if(str.begin(), str.end(), isNotABCD) == str.end());
}
int main()
{
string strand1;
cout << "Enter String 1:\n";
while ( cin >> strand1 && !isValidInput(strand1) )
{
cout << "Invalid Input";
system("cls");
cout << "Enter String 1:\n";
}
cout << "ok";
}
Update
You can also use a simpler version of isValidInput(), Thanks to #Blastfurnace for the suggestion.
bool isABCD(char c)
{
return (c == 'A') || (c == 'B') || (c == 'C') || (c == 'D');
}
bool isValidInput(std::string const& str)
{
return (std::all_of(str.begin(), str.end(), isABCD));
}
Update 2
You can also use a still simpler version of isValidInput(), Thanks to #JorenHeit for the suggestion.
bool isValidInput(std::string const& str)
{
return (std::find_first_not_of("ABCD") == std::string::npos);
}
Your question is unclear, but after examining your code I believe the problem is that for your loop condition you are using i <= strand1.length when you should be using i < strand1.length.
The loop condition you are using will check an index out of bounds of the string. In addition, you should not be incrementing i in the else statement as that is already done in the for statement. In the future, please clearly state your question along with any error codes you are getting.

Getline() always takes input

I am capturing video from my webcam and if the user hits the Enter key I take a picture. Then I ask "Is the picture okay?" to user and wait for an input. If he says "No", I keep doing the same thing, until he says "Yes".
But if he says "No", and in the meantime I type something in the terminal, getline() function writes whatever I type into its buffer, and when I ask the question again it goes directly to "invalid input" state.
How do I prevent this?
I have read a lot of questions regarding this and I tried to use cin.ignore() and cin.clear() before/after after I call getline(), but they didn't help.
// Do capturing here
string choice;
int choiceIsOkay = 0;
while (choiceIsOkay == 0)
{
cout << "Is the picture okay? (Y/N): ";
getline(cin, choice);
if ((choice == "Y") || (choice == "y"))
{
choiceIsOkay = 2;
}
else if ((choice == "N") || (choice == "n"))
{
choiceIsOkay = 1;
}
else
{
cout << "\nInvalid input\n";
choiceIsOkay = 0;
}
}
if (choiceIsOkay == 2)
{
runAlgorithm = 1;
break;
}
else choiceIsOkay = 0;
If I understand your issue, if user enters Some Random Text In, your program always jump in "Invalid input" and never stops to wait for users input. Following code should resolve your issue.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int runAlgorithm;
// Do capturing here
int i = 0;
while (i++ < 3)
{
int choiceIsOkay = 0;
string choice;
while (choiceIsOkay == 0)
{
cout << "Is the picture okay? (Y/N): ";
getline(cin, choice);
if ((choice == "Y") || (choice == "y"))
{
choiceIsOkay = 2;
}
else if ((choice == "N") || (choice == "n"))
{
choiceIsOkay = 1;
}
else
{
cout << "nInvalid inputn";
choiceIsOkay = 0;
}
// Ignore to the end of line
cin.clear();
}
}
return 0;
}

How do I loop a statement in c++

I want to loop a question and make it say "press Y to continue or N to quit" but I don't quite know how. I tried to do a while loop but they haven't worked well. Here's the code:
cout << "press Y to play again or anything else to close: ";
cin >> val;
if (val != "Y" && val != "y")
{
spelaIgen = false;
}
}
Best for you to use cases to make your selections of "Y or N". The attempt you were making would have made it so any character other than Y would quit.
bool correctVal = false;
char val;
while (!correctVal)
{
cout << "press Y to play again or N to close: ";
cin >> val;
switch(val)
{
case 'y':
case 'Y':
spelaIgen = false;
correctVal = true;
break;
case 'n':
case 'N':
spelaIgen = true;
correctVal = true;
break;
default:
cout << "\nInvalid entry!" << endl;
}
}
You could do something like this. Initialize your input variable, then use that variable as your while condition. Continue iterating your while loop until they enter something other than 'y' or 'Y'.
char val = 'Y';
while (val == 'Y' || val == 'y')
{
// Do stuff
cout << "press Y to play again or anything else to close: ";
cin >> val;
}
I am assuming you are using the standard namespace in C++ here. Try the following:
string val = "Y";
while (val == "Y")
{
cout << "press Y to play again or anything else to close: ";
cin >> val;
if (val != "J" && val != "j")
{
spelaIgen = false;
}
}

Reprompt user after invalid input-c++

I modified the original code and the first two invalid input prompts work fine. when I implement the same logic into this prompt to start a new game, my program will not recognize an invalid input, with any key entered it will start a new game.
void newGame()
{
char newGameChoice = 'a';
cout << "\n--------------------------------------------------------------------------------" << endl;
cout << "Press N to play a new game\n";
cout << "Press X to exit\n\n";
cout << "--------------------------------------------------------------------------------" << endl;
cin >> newGameChoice;
newGameChoice = toupper(newGameChoice);
if (newGameChoice == 'N');
{
char userIn = 'a';
char c = 'a';
game(userIn, c);
}
while (newGameChoice != 'N' || 'X')
{
cout << "--------------------------------------------------------------------------------";
cout << "\n Invalid input. Please try again.\n" << endl;
cout << "--------------------------------------------------------------------------------" << endl;
newGame();
}
}
Your problem is this:
if (begin != 'B');
{
...
cin >> begin;
begin = toupper(begin);
start(); <------
You're calling start() again, which will read yet another value into begin.
Please spend more time analyzing your code before posting for help, it will help you to grow as a developer much more.
while (newGameChoice != 'N' || 'X')
is equivalent to
while (newGameChoice != 'N' || 'X' != 0)
Maybe what you mean is
while (newGameChoice != 'N' || newGameChoice != 'X')
Edit:
The code is wrong, it has to be rewritten, here is a suggestion:
void newGame()
{
char newGameChoice = 'a';
while (true) {
while (true) {
cin >> newGameChoice;
newGameChoice = toupper(newGameChoice);
if (newGameChoice != 'X' && newGameChoice != 'N') {
// Wrong input print error message
} else {
break;
}
}
if (newGameChoice == 'X') {
return;
}
game('a', 'a');
}
}
Part of your problem is that your start() method isn't designed in the most logical way. Currently when an invalid input is given, you attempt to read in another input and call start() again. When you called start() for the second time it starts back at the beginning of the start() method with no knowledge of the previous input.
What you should do instead is use a while() loop when an invalid entry is given and don't continue until a proper input is entered.
void start()
{
...
//Get initial user input
while begin != 'B'
{
Keep getting input if wrong
}
game(userIn, c);
}

invalid input by the user

hey guys so this is my program, I need to notify the user that if hhe/she enters a letter other than w d b or w that is an invalid request. what ive done so far does this, but when i input a number to the dollars_withdraw or dollars_deposit or account_balance the program will do the transaction but also add the "invalid request" before going back to main loop. how do i change it so the program wont do that for numerical inputs for the withdraw deposit and balance?:
// Atm machine.cpp : Defines the entry point for the console application.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char user_request;
string user_string;
double account_balance, dollars_withdraw, dollars_deposit;
account_balance = 5000;
while(account_balance >0)
{
cout << "Would you like to [W]ithdraw, [D]eposit, Check your [b]alance or [Q]uit?"
<< endl;
cin >> user_string;
user_request= user_string[0];
if(user_request == 'w' || user_request== 'W')
{
cout << "How much would you like to withdraw?" << endl;
cin >> dollars_withdraw;
if (dollars_withdraw > account_balance || dollars_withdraw <0)
cout << "Invalid transaction" << endl;
else
account_balance = account_balance - dollars_withdraw;
cout << "Your new balance is $" << account_balance << endl;
}
if (user_request == 'd' || user_request== 'D')
{
cout << "How much would you like to deposit?" << endl;
cin >> dollars_deposit;
if (dollars_deposit <0)
cout << "Invalid transaction" << endl;
else
account_balance= account_balance + dollars_deposit;
cout << "Your new balance is $" << account_balance << endl;
}
if(user_request == 'b' || user_request == 'B')
{
account_balance= account_balance;
cout << "Your available balance is $" << account_balance << endl;
}
if(user_request == 'q' || user_request == 'Q')
break;
else
cout << "Invalid request " << endl;
}
cout << "Goodbye" << endl;
return 0;
}
Sure it does. Your code says:
If it is a 'w' do something
...
If it is a 'q' do something, else yell "invalid"
So if the user does not enter a 'q', the last 'else' block will always be executed. Either use else if throughout or change your code to use a switch statement:
// Either:
if (user_request == ...) {
...
} else if (user_request == ...) {
...
} else {
std::cout << "invalid";
}
// Or (better, faster):
switch (user_request) {
case 'q':
case 'Q':
...
break;
...
default:
std::cout << "Invalid request";
}
A third option would be to use continue:
while (...) {
user_request = ...
if (user_request == 'w' ...) {
...
continue; // In this iteration, no other code within the while loop is executed.
}
if (...)
...
}
This is a bad programming practice. Please use Switch Case for what you need to achieve. And put a "break" statement after every case branch.
chain your if statements into if, else-if, else-if, ..., else.
else statements only "know of" the if statement immediately previous. For example:
if (myNumber == 0)
{
// Triggers when myNumber is zero.
}
if (myNumber == 1)
{
// Triggers when myNumber is one.
}
else
{
// Triggers when myNumber is not one.
}
This can be fixed with else if statements. In your case it would look something like this:
if (user_request == w)
{
// ...
}
else if (user_request == d)
{
// ...
}
// ...
else cout << "Invalid request.";
In my old CS class, I'd do things like this:
string user_string;
do {
if(user_string) cout << "Enter a valid value!" << endl;
cin >> user_string;
} while(user_string != "w" && user_string != "d");
You need to use else if as follows:
if(user_request == 'w' || user_request== 'W')
{
...
} else if(user_request == 'd' || user_request== 'D')
{
....
} else if(user_request == 'b' || user_request== 'B')
{
.....
} else if(user_request == 'q' || user_request== 'Q')
{
...
} else
{
// Invalid request
}