Refine my code/program where did I go wrong? - c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int LordIronhead = 0;
char answer;
cout<<"Is Lord Ironhead present? Y/N.\n";
cin >> answer;
if (answer == 'Y')
{
LordIronhead=0;
}
else if (answer == 'N')
{
LordIronhead= LordIronhead+1;
}
cout<< ""<<LordIronhead<<"\n";
system("PAUSE");
return 0;
}
Every time I run the program and If I answer NO (N)
the result is always 0 instead of 1 (LordIronhead = LordIronhead + 1)
May I know where my error is?

Your code is fine in principle, but you might run into issues with the two-valued logic of 'answer' being checked against 'Y' and against 'N' with no fall-through case. I suspect you are running into EOL or case or character conversion issues, falling through both if's and thereby never changing the Lord.
For showing the problem, try an else statement:
else if (answer == 'N')
{
LordIronhead= LordIronhead+1;
} else {
std::cout << "Invalid answer '" << answer << "'" << std::endl;
}

Your code is correct but is sensitive to the case of user input (it treats user input of N and n differently). You'd remove a possible source of user confusion by converting the input to a known case before checking it. You can do this using either toupper or tolower
cin >> answer;
answer = toupper(answer);

I just tried this myself and found that if I answered N I got the expected answer (1). If I hit n, however, it came back as 0. Are you sure you're hitting N and not n?

Better using 1 and 0 instead of N and Y. Its more recognizable to the system

Related

Why does my if statement not run even if the condition is met?

I tried to make a simple program that asks the user a question and if the user answers correctly, it tells them that they are correct, but if they don't, it tells them to try again, and the code runs again. I did this using a while loop, if they answer correctly it breaks out of the while loop. But when i tested it even when i get the correct answer, it doesn't break out of the loop.
#include <iostream>
int main() {
int answer;
while (1 < 2) {
std::cout << "What is 3 + 5?";
answer = std::cin.get();
if (answer == 8) {
std::cout << "You are correct!";
break;
}
else {
std::cout << "Wrong answer! Try again";
}
}
}
Because the get function returns a character.
There is no existing encoding where the character '8' is equal to the integer 8.
Either you need to convert the character to its corresponding integer:
(answer - '0') == 8
Or compare against the character:
answer == '8'
If you really want to read integers, then I suggest you read using the input operator >> instead:
std::cin >> answer;
I think you should assign answer like that:
std::cin >> answer;
because get function gets the input as string and your answer variable is int.
So in the if statement, it checks "8" == 8 and that returns false.
Concluding, the whole code must be like that:
#include <iostream>
int main() {
int answer;
while (1 < 2) {
std::cout << "What is 3 + 5?";
std::cin >> answer;
if (answer == 8) {
std::cout << "You are correct!";
break;
}
else {
std::cout << "Wrong answer! Try again";
}
}
}

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!

how to allow multiple inputs in case of an incorrect data type entry in cpp?

I have a program which generates random number and asks user to keep guessing it until he/she gets it right. I want it to keep accepting new values even if i incorrectly enter any other data type by handling the error cases.
My problem is that when i am trying to run the below program, as soon i input a character and hit enter, it goes into an infinite loop. I tried using cin.ignore() and cin.clear() but that just makes the program stop after the first entry.
Can anyone please help me understand what is going on and how to achieve the desired output? Thanks in advance.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
int secret_num, guess;
srand(time(NULL));
secret_num=rand() % 101 + 0;
cout<<"Enter your guess between 0 and 100: ";
do
{
if(!(cin>>guess))
{
cout<<" The entered value is not an integer"<<endl;
}
else if( isnumber(guess))
{
if(guess>secret_num)
cout<<"Too high";
else if(guess<secret_num)
cout<<"too low";
cout<<endl;
}
}
while(secret_num!=guess);
if((guess==secret_num)| (isnumber(guess)))
{
cout<<"yes the correct number is "<<secret_num<<endl;
}
return 0;
}
Edit: Here is a screenshot of what the output looks like with cin.clear() and cin.ignore(1000,'\n') in my code, when i enter a number after entering character twice.
if (!(cin >> guess))
{
cout << " The entered value is not an integer" << endl;
cin.clear(); // clear must go before ignore
// Otherwise ignore will fail (because the stream is still in a bad state)
cin.ignore(std::numeric_limits<int>::max(), '\n');
}
By default cin.ignore will ignore a single character. If they type more than 1 char, it won't be enough, that's why I've modified it a bit.
if ((guess == secret_num) | (isnumber(guess)))
| is a bitwise operator [OR]
|| is the logical operator [OR]
But I think what you actually want is && (AND)
if ((guess == secret_num) && (isnumber(guess)))
There're several problems.
You should use cin.clear() and cin.ignore() as #José suggested.
What's isnumber()? I guess it's returning false so no hint message (i.e. "Too high" and "too low") is printed out, looks like it stops although it's just waiting the next input. And isnumber() doesn't make sense to me. guess has been declared as an int, it has to be a number, doesn't it?
if((guess==secret_num)| (isnumber(guess))) is unnecessary here. The loop won't end until the user input the correct number, this condition should have been statisfied.
You can use clear and flush
if(!(cin>>guess))
{
cout<<" The entered value is not an integer"<<endl;
cin.clear();
fflush(stdin);
}
This works if you are reading from console. Otherwise you can go with #José answer.
I would change the logic inside your loop as there are some useless tests. This works for me:
#include <iostream>
#include <limits>
#include <cstdlib> // You may take a look at <random> and <chrono>
#include <time.h>
using std::cout;
using std::cin;
int main() {
srand(time(NULL));
int secret_num = rand() % 101;
cout << secret_num << '\n';
cout << "Enter your guess between 0 and 100:\n";
int guess = -1;
do {
cin >> guess;
if ( cin.eof() )
break;
if ( cin.fail() ) {
cout << "The entered value is not an integer, please retry.\n";
// clear the error flag
cin.clear();
// ignore the rest of the line
cin.ignore(std::numeric_limits<int>::max(),'\n');
// clear the value of the variable
guess = -1;
continue;
}
// now we know that guess is a number
if ( guess > secret_num )
cout << "Too high\n";
else if ( guess < secret_num )
cout << "Too low\n";
else {
cout << "Yes the correct number is " << secret_num << std::endl;
break;
}
} while ( true );
return 0;
}

My while statement is getting infinite loop? [closed]

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 7 years ago.
Improve this question
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
//this program will let the user input their assignment score and see their letter grade
int main() {
int score;
cout << "Input your score: ";
//to make the while loop
int x = 1;
while (x == 1) {
cin >> score;
if (score >= 90){
cout << "\nA";
break;
}
else if (score >= 80) {
cout << "\nB";
break;
}
else if (score >= 70) {
cout << "\nC";
break;
}
else if (score >= 60) {
cout << "\nD";
break;
}
else if (score >= 0) {
cout << "\nF";
break;
}
else
cout << "\nInvalid input";
}
}
I'm trying to write a program that let the user input their score for an assignment and display their resulting letter grade. If the user input is not a valid score, it prints "Invalid input" and should ask for user input again. However, when I actually run the program and type in an invalid value, it goes into an infinite loop of printing "Invalid input". Why is this? Thanks in advance.
When the user enters invalid input, cin >> score fails and leaves an error flag set on the stream.
Subsequent read operations just don't do anything until you clear that flag with std::basic_ios::clear().
Furthermore, since the read failed, score has some unspecified value (as you did not initialise it), and apparently on your test runs that unspecified value happens not to match any of those continues, so you never hit a break.
Instead of just:
std::cin >> score;
Try this:
if (!(cin >> score)) {
// If reading into an int failed, we come here
cout << "Invalid value! Try again" << endl;
// Clear error flag
cin.clear();
// Restart the loop
continue;
}
You may also need to ask the stream to eat up newlines in the input buffer. If you get the "Invalid value!" message twice, look up on SO how to do that.
you set x=1 and check if x==1. For the compiler it seems that it could be an infinite loop because it's unsure if a break would happen, that's why it's only a Warning and not an Error. For that behaviour you don't even need to vast the variable x , you could use while(true) too.

Char or String?

Does it matter if I use a string or char for a simple input function? (aka y/n)
This is what I'm using at the moment:
using namespace std;
string somestr;
getline(cin,somestr);
if(somestr.empty())
{ //do something }
else if (somestr == "y"){
//do something else
}
else{}
And if it makes more sense to user char what would be the equivalent char code to this?
Yes, it matters, because std::string cannot be compared with a char using ==. You can compare it with a string literal:
if (somestr == "y")
or you can test the initial element of the std::string:
if (somestr[0] == 'y')
In the latter case, you might want to check the length as well, otherwise you would accept such inputs as "yacht" and "yellow." Comparing with a string literal containing the expected text is probably a better choice for most use cases.
I think James McNellis gives good rationale for why you would use either case. Personally, if you're asking a "yes/no" question, I find the single character easier because it minimizes the number of different scenarios you have to deal with.
Here's some sample code that you could use to read an answer from the user via a single character:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
//keep looping until the user enters something valid
while(true)
{
char answer;
cout << "Does this sound good (y/n)? ";
cin >> answer;
if(answer == 'y' || answer == 'Y')
{
//user entered yes, do some stuff and leave the loop
cout << "You answered yes!" << endl;
break;
}
else if(answer == 'n' || answer == 'N')
{
//user entered no, do some stuff and leave the loop
cout << "You answered no!" << endl;
break;
}
else
{
cout << "You did not enter a valid answer. Please try again." << endl;
//if we got bad input (not 'y'/'Y' or 'n'/'N'), wipe cin and try again
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n');
}
}
}
If you're planning on reading more than a single character answer though, then I think you're probably fine with getline and doing your reasoning that way.
It is better to use char because you only need to store one character
using namespace std;
char chr;
getline(cin,chr);
if(chr == null)
{ //do something }
else if (chr == "y"){
//do something else
}
else{}