Get yes/no in console always fails - c++

I'm trying to make a program that will run over and over again, provided the user says yes every time. Unfortunately, it doesn't seem to recognize when I input yes or no into it, and always does the default "Come again?" message. This is the code I'm using to get the input from the console:
bool getYN(){
bool confirmed = 0;
bool answer = 0;
string input;
while(!confirmed){
getline(cin, input, '\n');
transform(input.begin(), input.end(), input.begin(), toupper);
if(input.c_str() == "Y" || input.c_str() == "YES"){ //If the user says yes
confirmed = 1;
answer = 1;
} else if(input.c_str() == "N" || input.c_str() == "NO"){ //If the user says no
confirmed = 1;
answer = 0;
} else { //If the user says something else entirely
printf("\nCome again? (Y/N) ");
};
};
return answer;
};
I have included <string> and <algorithm>. For some reason, it always acts like it's not getting y/yes or n/no when I type them in. It just keeps asking me to answer again.

if(input.c_str() == "Y" || input.c_str() == "YES"){ //If the user says yes
confirmed = 1;
answer = 1;
} else if(input.c_str() == "N" || input.c_str() == "NO"){ //If the user says no
confirmed = 1;
answer = 0;
}
You should not be doing c-string comparisons like this. You're taking the address of a char and comparing against the address of a text-allocated object. Of course the comparison is going to return false.
With c++ strings, simple operator== comparisons are valid:
if(input == "Y" || input == "YES"){ //If the user says yes
confirmed = 1;
answer = 1;
} else if(input == "N" || input == "NO"){ //If the user says no
confirmed = 1;
answer = 0;
}

#include <iostream>
#include <string>
using namespace std; // For speed
int main()
{
bool saidYes = false;
string input;
while (!saidYes)
{
cout << "Input yes or no: ";
getline(cin, input);
if (input == "no" || input == "n" || input == "NO")
{
saidYes = true; // breaks the loop
}
if (input == "y" || input == "Y" || input == "yes" || input == "YES")
{
saidYes = false;
}
}
return 0;
}
You can use the above example to eliminate a huge portion of unnecessary code, I chose not to add the else statement but it will work if you add that here as well.
You can also condense this code even further but this was only intended to be a simple example as to how to better get this working for you!
As it was said above you can use == to compare the strings, if you're coming from certain other languages it can be an annoying change to get used to lol.
I have included string and algorithm. For some reason, it always acts like it's not getting y/yes or n/no when I type them in. It just keeps asking me to answer again.
algorithm is not required for what you're trying to do, and your making the reading and acceptance of the string input much more difficult than it needs to be.
If you look above you'll see the string input; This is going to be your variable that you can use to store the user input string into.
You'll also notice getline(cin, input); This is what you can use to "read" the string that the user enters when they're prompted to.
#Kelvin Shadewing My initial answer was only directed at your Question, this next example is directed to your comment to me below!
So you've got quite a few options but assuming that you want the user to input either yes or no and depending on the input you want to produce a specific result while ensuring that the user is prompted over and over again to input either yes or no all you have to is modify my original answer like so.
#include <iostream>
#include <string>
using namespace std; // For speed
int main()
{
bool saidYes = false;
string input;
while (!saidYes)
{
cout << "Input yes or no: ";
getline(cin, input);
if (input == "no" || input == "n" || input == "NO")
{
saidYes = true;
cout << "you said no" << endl;
/* breaks the loop by changing the
bool (true or false flag) to true, if you want to produce a specific result,
whether it's a simple output statement or a function call you can put it here
*/
}
else if (input == "y" || input == "Y" || input == "yes" || input == "YES")
{
saidYes = true;
cout << "You said yes" << endl;
/* breaks the loop by changing the
bool (true or false flag) to true, if you want to produce a specific result,
whether it's a simple output statement or a function call you can put it here
*/
}
else saidYes = false;
}
return 0;
}

I've modified my code based on the current best answer, but I've also optimized it so that confirmed is no longer necessary.
bool getYN(){
bool answer = 0;
string input;
while(!answer){
getline(cin, input, '\n');
transform(input.begin(), input.end(), input.begin(), toupper);
if(input == "Y" || input == "YES"){
answer = 2;
} else if(input == "N" || input == "NO"){
answer = 1;
} else {
printf("\nCome again? (Y/N) ");
};
};
return answer - 1;
};
Small optimization, sure, but every little bit counts.

Related

I need help on this C++ yes/no problem while using logical operators

So the problem is: Write a program that prints the question "Do you wish to continue?" and reads the input. If the user input is "Y", "Yes", "YES", then print out "Continuing". If the user input is "N" or "No", "NO" then print out "Quit". Otherwise, print "Bad Input". Use logical operators.
So far this is all the code that I have written. I know that it is not complete, and I do not know what else I need to add to the code.
#include <iostream>
using namespace std;
int main() {
char response;
cout << "Do you wish to continue?" ;
cin >> response;
if (response == 'Y'){
cout << "Continuing";
}
else if (response == 'N'){
cout << "Quit";
}
else if (response != 'N' || 'Y'){
cout << "Bad input";
}
return 0;
}
Update: so I edited my code and it is still giving me a bunch of errors. It's making me frustrated lol. Keep in mind I'm a beginner and we haven't learned loops yet. Sorry for the headache!
#include <iostream>
#include <string>
using namespace std;
int main() {
char response;
string help;
cout << "Do you wish to continue?" ;
cin >> response, help;
if (response == 'Y' || help == "Yes" || help == "YES"){
cout << "Continuing";
}
else if (response == 'N' || help == "No" || help == "NO"){
cout << "Quit";
}
else if (response != 'N' || response != 'Y' || help != "Yes" || help != "YES" || help != "No" || help != "NO"){
cout << "Bad input";
}
return 0;
}
First off I think this is a great start. Sounds like you are new to C++ so here are some suggestions:
1) Your response variable can only contain a character. I would suggest including string and changing the response to take a string from the user for 'Y', "Yes", etc.
2) I suggest wrapping your code in a while loop with an exit condition.
3) Each of your logic branches should include a return integer. This will give the program an exit condition if the logical conditions are met.
I know I haven't given you the answers fully. If you are truly stuck, reply back and we can walk through.
A simple way is to simply convert the user's answer to uppercase or lowercase. By doing this, you can simply use the lower case.
For your loop, you could for example use a "do..while".
#include <iostream>
#include <string>
using namespace std;
int main() {
int stop = 0;
string response;
//Continue until the user choose to stop.
do{
//-------------
// Execute your program
//-------------
cout << "Do you wish to continue? ";
cin >> response;
//-------------
//Convert to lower case
for (string::size_type i=0; i < response.length(); ++i){
response[i] = tolower(response[i]);
}
//-------------
//Check the answer of the user.
if (response.compare("y") == 0 || response.compare("yes") == 0){
cout << "Continuing \n";
}
else if (response.compare("n") == 0 || response.compare("no") == 0){
cout << "Quit \n";
stop = 1;
}
else{
cout << "Bad input \n";
}
}while(stop == 0);
return 0;
}
Like you said in the question, we care about Y,Yes,YES,N,No and NO. For anything else we need to print "Bad Input". Think about how you'd be storing these responses (hint: Sam Varshavchik's answer).
Once you've taken care of extracting user input, you'd want to check what the user actually entered and proceed accordingly. From your question it seems "if else" would do. You need to change the conditionals for your "if else ifs" because
you have 3 conditions for one type of response: Y, Yes and YES need one output - "continuing" while N, No and NO require a different output - "Quit" and for all others we print "Bad input". Think about what your conditionals should be and your if statement should look something like:
if (response == "Y" || response == "Yes" || response == "YES")
and then handle the case accordingly. You'd want to do the same for your No conditions and finally handle the case for all others. I'd suggest having your code like so:
if( conditionals for Yes){
//Code for Yes input
}
else if( conditionals for No){
//Code for No input
}
else{
//Code for all other inputs
}
It is tempting to give you the full answer but think about how your program needs to flow and proceed from there, you've almost got it!
If you have more questions post here and we'd be glad to help!

Having to hit enter twice with cin.getline()

I know for a fact similar questions have been asked before but I really can't figure out what's wrong with my code specifically. For some reason if I input "n" I have to press enter twice. But if I input "y", everything works fine and the code moves to the next section. My code is as follows:
do{
try {
if (test) cout << " Re-enter: ";
test = false;
getline(cin, choice);
checkinput(choice);
}
catch (int flag) {
if (flag == 1){ cout << "Error: Input must be y or n."; test = true; }
}
} while (test);
and the checkinput function is as follows:
// function for checking the input of y/n
string checkinput(string c) {
if (c != "Y" && c != "y" && c != "N" && c != "n") {
throw 1;
}
if (cin.fail()) throw 1;
return c;
}
I think you are trying to do too much here. You can simplify this.
There is no need to throw and catch exceptions inside checkinput. Since there is only two cases you can use a boolean. Secondly, you are returning c. I don't know why you are doing that, it isn't being used. You should instead, return a boolean.
checkinput becomes:
bool checkInput(string c) {
if (c.length() > 1)
return false;
return c == "Y" || c == "y" || c == "N" || c == "n";
}
Now you can simplify the do-while and remove the try statement. Additionally, there is no need for the test variable now since we are successfully grabbing any input:
int main() {
string choice = "";
do {
cout << "Enter yes or no (y/n): ";
getline(cin, choice); // or cin >> choice;
bool check = checkInput(choice);
if (!check)
cout << "Error: Input must be y or n." << endl;
} while (true);
}
You may also simplify this further but that will be at the cost of readability. Good luck!

c++ Validating a Double in a String

Please excuse any amateur mistakes, I'm still quite new to this. For my class we need to convert a double input to a string to use in a different part of the project. The verification for the integers worked just fine and I attempted using some of the code from this previous question Validating a double in c++
though, much to my chagrin it did not work.
Here is my code:
string input;
bool valid;
double num;
//Verification of valid inputs
do
{
valid = true;
cout << "What is the " << name << " rate of the population? (% per year): ";
getline(cin, input);
num = input.length();
if (num == 0)
{
cout << "\nNo data was entered, please enter a number.\n";
valid = false;
}
else
{
for (double i = 0; i < num; i++)
{
if (input.at(i) < '0' || input.at(i) > '9')
{
cout << "\nPlease enter a valid, positive number.\n";
valid = false;
break;
}
}
}
} while (valid == false);
return stod(input);
Thanks.
Edit:
I just found this How do i verify a string is valid double (even if it has a point in it)? and I can safely say I have no idea what is going on.
If you are really keen to do it manually, take a look at the following methods:
How to manually parse a floating point number from a string
https://www.daniweb.com/programming/software-development/code/217315/c-function-stod-string-to-double-convert-a-string-to-a-double
and read the comments. It's not quite straightforward, but it should work. Or even better, check the code of stod from C++.
Why are you using a double as an index for the string? Also, I'd skip using a ++ for increment a double.
Figured it out.
Just had to add something to an if statement.
if ((input.at(i) < '0' || input.at(i) > '9') && input.at(i) != '.')
{
cout << "\nError! illegal character was entered.\n";
valid = false;
break; // 12w345
if (input.at(i) == '.')
ct++;
if (ct > 1)
{
cout << "Error! Only one dot allowed.";
valid = false;
With ct being an integer with value 0 to count the dots and ensure only one was entered.

How do I allow different amounts of input in c++

Assume all variables exist (didnt bother declaring them all here)
if(input=='R') goto restart;
if(input=='X') exit(0);
if(input=='D') moveRight(edgeLength, board, score);
if(input=='S') moveDown(edgeLength,board, arrSize);
if(input=='A') moveLeft(edgeLength,board, arrSize);
if(input=='W') moveUp(edgeLength,arrSize,board);
if(input=='P')
{
cin>> number>>position;
board[position]=number;
}
This input is put into a loop, so the user is asked for input so long as this game is in play.
My goal is to allow for input such as
p 3 50
to place the number 50 at index position 3.
With my current code, I have to type 'p' press enter, then the next two numbers.
However, id like the program to detect 'p 3 50' (enter) in one go, as 'D'(enter) signifies moveRight.
I hope I'm being clear in my question.
cin >> input >> number >> position;
if(input=='R') goto restart;
else if(input=='X') exit(0);
else if(input=='D') moveRight(edgeLength, board, score);
else if(input=='S') moveDown(edgeLength,board, arrSize);
else if(input=='A') moveLeft(edgeLength,board, arrSize);
else if(input=='W') moveUp(edgeLength,arrSize,board);
else
{
//whatever statements for last condition;
}
If you want to capture all three input at once, you can get the input first, then execute the respective actions according to the received inputs.
Added: Using if or else-if depends on situation. From what I see here in your code snippet, else-if is better than if because you can only have one input type everytime. Once matching character is found, (example 'D'), it will stop reading the codes below (which should be the way as it is unnecessary to check the rest of the conditions whether input is 'S' or 'A' or 'W' anymore since you already got the input). Makes your code fun slightly faster too, by preventing unnecessary checking on the conditions.
Proof Of Concept:
//Example
void fncOne()
{
cout << "This is function one" << endl;
}
void fncTwo()
{
cout << "This is function two" << endl;
}
int main()
{
char input;
int number, position;
cin >> input >> number >> position;
if (input == 'A') fncOne();
else if (input == 'B') fncTwo();
}
Input: A 3 5
Output: This is function one
Well, first you're going to want to get user input as a string rather than individual types.
std::string input;
std::cin >> input;
then you'll want to parse that string based on how many words for key words/characters.
e.g.
std::vector<std::string> words;
std::stringstream stream(input); std::string temp;
while(stream >> temp)
words.push_back(temp);
if(words.size() == 3){
if(words[0][0] = 'p'){
int number = std::stoi(words[1]);
int position = std::stoi(words[2]);
board[position] = number;
}
else
... get input again ...
}
else if(words.size() > 1){
... get input again ...
}
else{
char c = words[0][0];
if(c == 'w')
moveUp(edgeLength,arrSize,board);
else if(c == 's')
moveDown(edgeLength,board, arrSize);
else if(c == 'a')
moveLeft(edgeLength,board, arrSize);
else if(c == 'd')
moveRight(edgeLength, board, score);
else if(c == 'x')
exit(0);
else if(c == 'r')
goto restart;
else
... get input again ...
}
Of course this is only one way if you want to type one string then press enter only once.

using user input such as YES and NO to control program flow in C++

I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No = "NO";
if (input == no)
{
cout << "testone" << endl;
}
if (input == yes)
{
cout << "test two" << endl;
//the rest of the program goes here i guess?
}
else
{
cout << "you entered the wrong thing, start again" << endl;
//maybe some type of loop structure to go back
}
but I can't seem to get any variations of this to work, i could make the user type a 0 or 1 instead but that seems really stupid, i'd rather it be as natural as possible, users don't speak numbers do they?
also i need to be able to simply add more words, for example "no NO No noo no n" all would have to mean no
hopefully that makes some sense
also i would love to make this using a window but i've only learned basic c++ so far not even that and i cant find any good resources online about basic windows programming.
You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type in "NO" then it will still go into that last else block.
First of all, input must be std::string, not int.
Also, you've written yes and no wrong:
v
if (input == No)
// ..
// v
else if (input == Yes)
^^^^
If you want your program to work with "no no no ..", you could use std::string::find:
if( std::string::npos != input.find( "no" ) )
// ..
The same with "Yes".
Also, you could do this to be almost case-insensitive - transform the input to upper-case letters (or lower, whatever ), and then use find.This way, yEs will be still a valid answer.
bool yesno(char const* prompt, bool default_yes=true) {
using namespace std;
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
}
string line;
if (!getline(cin, line)) {
throw std::runtime_error("yesno: unexpected input error");
}
else if (line.size() == 0) {
return default_yes;
}
else {
return line[0] == 'Y' || line[0] == 'y';
}
}
string input;
cin >> input;
if (input == "yes"){
}
else if (input == "no"{
}
else {
//blah
}