I am tackling one of the exercises in Stroustrup's book whereby I have to design a program to guess a number between 1-100 that the user is thinking of by asking questions i.e. "Is it less than 50?" etc. I can't ask more than 7 questions to get to the answer.
So far I have something like this:
string answer;
cout << "Think of a number between 1 and 100.\n";
cout << "Is it even or odd? (E/O)\n";
cin >> answer;
if (answer == "E")
{
cout << "Is it less than 50? (Y/N)\n";
cin >> answer;
if (answer == "Y")
{
cout << "Is it less than 25? (Y/N)\n";
cin >> answer;
if (answer == "Y")
{
cout << "Is it less than 15? (Y/N)\n";
cin >> answer;
if (answer == "Y")
{
cout << "Is it less than 9? (Y/N)\n";
cin >> answer;
if (answer == "Y")
{
cout << "Is it less than 5? (Y/N)\n";
cin >> answer;
if (answer == "Y")
{
cout << "Is it less than 3? (Y/N)\n";
cin >> answer;
if (answer == "Y")
{
cout << "Your number is 2.";
}
}
}
}
}
}
}
I feel this is really bad because I have only one path of the flow diagram and already this program is quite long. Is there a more efficient way to do this?
Basically, you want to either remove half or add half to the number you guessed before, based on what the user said. If you ask for input in a loop, you can simply add or remove half of the number each time, asking the new number.
So basically, instead of hard coding each question, you just ask the same question every time but using the last number / 2 or + (/2) in a loop.
I assume you don't really want us to write the code for you, so I wont. I'm sure you can figure it out with that clue! Check out for/while loops, as you need those to do this.
Related
I'd like to write a program that asks the user if he/she tends to work as a delivery service. If yes he/she should have some eligibilities. If the user have them he/she can be hired.
I've written some code, but when I compile and run it, after the user answered 2 first questions the cmd doesn't let the user to enter his/her answers for remaining questions (the cin code doesn't work anymore or as though there is no cin code.)
What's wrong with my code? Why cin doesn't work after 2 first question but it works at first 2 ones? How can I make it work?
#include <iostream>
using namespace std;
int main()
{
string answer{}, ssn1{}, a, b;
int age{0};
bool parental_consent{false}, ssn{false}, accidents{false};
cout << boolalpha;
cout << "Do you want to work as a local delivery (Y/N)? \n";
cin >> answer;
if (answer == "Y" || answer == "y")
{
cout << "Do you have any social security number(yes/no)? \n";
cin >> ssn;
ssn = ("yes" || "Yes");
cout << "How old are you? \n";
cin >> a;
cout << age;
cout << "If you're between 15 and 18 years old please answer this question: \n Do have parental "
"consent(yes/no)? \n";
cin >> ssn1;
// cout << parental_consent;
parental_consent = ("yes" || "Yes");
cout << "Have you ever had any accidents? \n";
cin >> b;
accidents = ("yes" || "Yes");
if ((age >= 18 || (age >= 16 && parental_consent)) && ssn && !accidents)
{
cout << "Yes, you can work.";
}
else if (age <= 15)
{
cout << "Sorry, your age is not eligble!\n";
}
}
else
cout << "sorry to hear that.";
cout << endl << endl << endl;
return 0;
}
From cppreference:
If the type of v is bool and boolalpha is not set, then if the value to be stored is 0, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.
From the code, i can see that the second std::cin doesn't have boolalpha and is assigning to a bool value. This causes td::ios_base::failbit to be assigned to err, preventing other input. You have to do std::cin.clear(); to be able to use std::cin >> a; again.
If it still skips
Try using cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after every std::cin to clear out whitespaces that causes it to return immediately.
It seems you wanted to use std::boolalpha to convert your questions into boolean. This obviously didn't work because you used it on std::cout to use it on input you need to use it on std::cin like this:
cin >> boolalpha >> ssn;
But you can't answer yes or Yes, you need to answer true or false so it's better to just std::cin >> answer and compare the string instead like this:
#include <iostream>
int main()
{
std::string answer{};
int age{ 0 };
bool parental_consent{ false }, ssn{ false }, accidents{ false };
std::cout << "Do you want to work as a local delivery (Y/N)? \n";
std::cin >> answer;
if (answer == "Y" || answer == "y")
{
std::cout << "Do you have any social security number(yes/no)? \n";
std::cin >> answer;
ssn = (answer == "yes" || answer == "Yes");
std::cout << "How old are you? \n";
std::cin >> answer;
age = atoi(answer.c_str());
if (age >= 15 && age <= 18) {
std::cout << "If you're between 15 and 18 years old please answer this question: \n Do have parental "
"consent(yes/no)? \n";
std::cin >> answer;
parental_consent = (answer == "yes" || answer == "Yes");
}
std::cout << "Have you ever had any accidents? \n";
std::cin >> answer;
accidents = (answer == "yes" || answer == "Yes");
if ((age >= 18 || (age >= 16 && parental_consent)) && ssn && !accidents)
{
std::cout << "Yes, you can work.";
}
else if (age <= 15)
{
std::cout << "Sorry, your age is not eligble!\n";
}
}
else {
std::cout << "sorry to hear that.";
}
std::cout << std::endl << std::endl << std::endl;
return 0;
}
cin>>answer;
if(answer=="yes"||"Yes"== answer)
ssn=true;
This line will only make the left of the = being true:
ssn = ("yes" || "Yes");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm just starting to learn C++ for school, and I'm having trouble completing a school project requiring the use of if/else statements. The project requires code that works as:
example of working code
My code looks like this:
#include <iostream>
using namespace std;
int ontime;
int zip;
int work;
int main()
{
cout << "Welcome to the DIG3873 System." << endl;
cout << "Did the student submit the exam on time (Y/N)? ";
cin >> ontime;
if (ontime == 'Y' || 'y') {
cout << "Did the student zip the file (Y/N)? ";
cin >> zip;
if (zip == 'Y' || 'y') {
cout << "Did the student's code work as requested (Y/N)? ";
cin >> work;
if (work == 'Y' || 'y') {
cout << "Congratulations, YOU PASS. "<< endl;
} else if (work == 'N' || 'n') {
cout << "YOU FAIL " << endl;
} else {
cout << "Please enter a valid response. " << endl;
}
} else if (zip == 'N' || 'n') {
cout << "YOU FAIL " << endl;
} else {
cout << "Please enter a valid response. " << endl;
}
} else if (ontime == 'N' || 'n') {
cout << "YOU FAIL " << endl;
} else {
cout << "Please enter a valid response. " << endl;
}
}
Unfortunately, it's not working as I would have hoped. When it runs, it lets me answer the first statement, then just drops all the other cout statements and a bunch of "YOU FAIL"s and ends the program. We haven't learned anything beyond if/else statements, so I was pretty lost looking at similar coding issues where people recommended using loops instead. Sorry for such a beginner's issue with not understanding if/else statements, thanks!
The expression zip == 'Y' || 'y' will always be true.
That's because the only comparison that's made is zip == 'Y'. The expression is really (zip == 'Y') || ('y'). That is, you test if zip is equal to 'Y'; Or if 'y', just 'y', no comparison or anything. And since 'y' is non-zero it's true.
You need to explicitly compare zip with both values: zip == 'Y' || zip == 'y'.
The same is valid for your other conditions as well.
You also have another problem, and that is you not actually reading characters but integers. If you have int variables and are using the formatted input operator >>, the input will attempt to parse the input as an integer.
To read characters you need to use char.
So for some reason no matter what I enter into this If-Else statement it returns with a "Program Aborted" as if I entered the wrong requested answers...very confused and I can't seem to find anything relevant enough around the site!
int ch;
cout << "Do you have any extra credit points? (Enter Y/y or N/n)" << endl;
cin >> ch;
int ExtraCredit;
if (ch == 'Y' || ch== 'y')
{
cout << "Enter the number of extra credit points: ";
cin >> ExtraCredit
}
else if (ch!='n' || ch!='N' || ch != 'y' || ch != 'Y')
{
ExtraCredit=0;
cout<< Invalid entry. Program Aborted." << endl;
return 0;
}
The issue appears very early:
int ch; // are you sure this should be an int?
cout << "Do you have any extra credit points? (Enter Y/y or N/n)" << endl;
cin >> ch;
cin behaves differently on int typed variables than on chars. When you enter "y" or "n" at the keyboard, cin will fail.
You can check whether cin failed by calling its fail() method, like so:
int num;
std::cout << "Enter a number: ";
std::cin >> num;
if (std::cin.fail()) {
std::cout << ":(" << std::endl;
} else {
std::cout << "Your number was " << num << std::endl;
}
ints and chars are separate types, even though they can be compared based on the ASCII value of the char in C++. Because they are defined as separate types, when your code gets to the line cin >> ch and ch is of type int, it waits for something to be entered. The prompt tells the user to enter a char, and they do. The code sees the char, and as it wasn't an int, nothing is read in and the value of ch is correctly determined by your code to be not y, Y, n, or N. If you'd like to cin a char, declare char ch;. If you'd like to have an int, prompt the user to enter a number.
I need help debugging my code. So I made a program that adds and subtracts numbers but when I implemented a do-while loop to replay the program, the actual program closes and does not perform the do-while loop and does not replay the program. Is their something wrong with my code?
P.S. I am also using codeblocks IDE
#include <iostream>
using namespace std;
int main()
{
// Addition and Subtraction Calculator
int a_number, number1, number2, sum, number3, number4, subsum, again;
// subsum = subtracted sum
// number1 and number2 are variables that hold the users input for addition
// number3 and number4 are variables that hold the users input for subtraction
do
{
cout << "Addition & Subtraction Calculator" << endl;
cout << "-------------------------------------------" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "Please enter a number [1 or 2]" << endl;
cin >> a_number;
while (a_number < 1 || a_number > 2)
{
cout << "Please enter either 1 or 2" << endl;
cin >> a_number;
}
switch (a_number)
{
case 1:
cout << "Please enter a number" << endl;
cin >> number1;
cout << "Please enter another number" << endl;
cin >> number2;
sum = (number1 + number2);
cout << "The sum is " << sum << endl;
break;
case 2:
cout << "Please enter a number" << endl;
cin >> number3;
cout << "Please enter another number" << endl;
cin >> number4;
subsum = (number3 - number4);
cout << "The answer to the subtraction problem is: " << subsum << endl;
break;
}
cout << "Do you want to try again? [y/n]" << endl;
cin >> again;
}
while (again == 'y' || again == 'n');
return 0;
}
OK. So the OP is using an int where they should have used a char. That covers the immediate problem. int again should be char again.
But there is an important point the other answers have missed.
int again;
cin >> again;
The user input will be converted into an integer as required by again. Inputting y or n fails to convert to an integer as neither y nor n are numbers and cannot be converted. again remains unchanged, keeping whatever junk value happened to be sitting at that spot in memory and might actually be a y or an n, but more importantly cin is now in an error state that needs to be cleared before continuing.
cin would have notified the OP of this if it had been tested. So let's test it.
int again;
if (cin >> again)
{
// got good input. Do something with it.
}
else
{
// got bad input.
cin.clear();
// that bad input is still in the buffer and needs to be removed
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// the above line will wipe out everything to the end of the stream or
// end of line, whichever comes first.
}
Why this is important: Because the OP is doing a lot of numeric input with cin and none of it is checked for validity. For example:
cout << "Please enter a number [1 or 2]" << endl;
cin >> a_number;
The program is broken completely and cannot exit without a kill signal if the user types in anything but a number.
Always check the error state and return codes. They are there to help. Always validate user input before using it. Users are evil and will try to break your program. Don't let them.
use char again; instead of int again;
in your code again is int and when in (again == 'y' || again == 'n')you compare again (an int) with a char, that does not make sense
You need to change the again variable to a char datatype because you need to store text. Something like this:
char again;
You also need to change the while statement to:
while(again != "n");
Or
while(again == "y");
I’m a beginning C++ programmer and this is only my second program... It’s a simple money converter between dollars and Euros. The problem I have is that if I put in a NaN value, it’ll say so and ask again but quit. Does anyone know how to make it wait until the user types something else? Also at the second cin >> user_dollar I’m getting an error that says “Reference to overloaded function could not be resolved; did you mean to call it?” Sorry that this is so long and thanks~
Here is my code. I’m using Xcode on my MacBook Pro.
#include <iostream>
using namespace std;
int main() {
string choice;
int user_dollar;
int user_euro;
cout << "Dollars to Euros (type ‘Dollars’) or Euros to dollars (type ‘Euros’)? ";
cin >> choice;
if (choice == "Dollars" || choice == "dollars") {
cout << "Enter dollar amount: ";
cin >> user_dollar;
if (isdigit(user_dollar) != true){
cout << "That’s not a number... " << endl;
cout << "Enter dollar amount: " << endl;
*cin >> user_dollar;*
}
else {
cout << "That is " << user_dollar / 1.13 << " Euros." << endl;
}
}
else if (choice == "Euros" || choice == "euros") {
cout << "Enter Euro amount: ";
cin >> user_euro;
cout << "That is " << user_euro * 0.89 << " dollars." << endl;
}
}
You need to flush the cin buffer before second use of cin. Something like
cin.clear();
cin.ignore(INT_MAX,'\n');
cin >> user_dollar;
Take a look at this thread for more details on flushing the buffer.
Since the type of the user_dollar variable is an int, it can only hold an integer. If someone types something besides a number (like "hi"), it cannot be stored in user_dollar.
When you call cin >> user_dollar, and the user enters a non-number, it fails and does not change user_dollar. Since nothing else has set user_dollar at that point, it could be anything--semi-random garbage. You are currently checking that garbage with isdigit(). And isdigit() is not for checking integers read directly using cin.
You can check if it failed to read a number by calling fail(), use clear() to reset whether there was an error, and ignore() to flush the buffer as Igor shows.
As philipxy said, you can use a while loop to keep asking until a number was successfully read.