C++ If Statement Loop Structure Issue [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to make a little program that will ask the user if they're human and then do a bunch of other stuff afterwards. The following is a snippet of the code where the user is asked whether they're human. Now if you enter anything other than yes or no, the program then loops with the 'goto' statement. The problem that I'm having is that the if statements, when they end go to this 'goto' statement thus looping when the program should end. How can I get the goto statement to be exclusively part of the second else if statement? Failing that, is there another loop structure that I should use? Any help would be greatly appreciated.
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main ()
{
go:
string i;
cout << "Are you Human?>"<<endl;
cin >> i;
if (i == "yes"&&"Yes")
cout<< "Cool"<<endl;
else if (i == "no"&&"No")
cout<< "Interesting"<<endl;
else if (i!= "yes"&&"Yes"&&"no"&&"No")
cout<< "A simple Yes or No will suffice..."<<endl;
goto go;
system("pause");
return 0;
}

You really need to learn how to write if-conditions in C++. For example, you need to change
if (i == "yes"&&"Yes")
to
if (i=="yes" || i=="Yes")
to be able to check i is yes or Yes. And change others accordingly.
You need to use braces to define scopes instead of just code indentation (this is just for you, not for compiler). For example,
else if (... ...)
{
cout<< "A simple Yes or No will suffice..."<<endl;
goto go;
}

You have to place the goto statement in the code block of this else-if.
else if (i!= "yes"&&"Yes"&&"no"&&"No")
{
cout<< "A simple Yes or No will suffice..."<<endl;
goto go;
}
Also take into account that conditions as
else if (i!= "yes"&&"Yes"&&"no"&&"No")
or
if (i == "yes"&&"Yes")
are invalid, In fact the last condition is equiavelnt to
if ( ( i == "yes" ) && ( "Yes" ) )
as "Yes" is implicitly converted to pointer to its first character then expression "Yes" will be always equal to true and the condition is equivalent to
if ( i == "yes" )
Also it is a very bad idea in general to use goto statement. You should forget that there is goto statement in C/C++. Instead you should use control structures as while or do-while.
For example
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main ()
{
string s;
do
{
cout << "Are you Human?>" < <endl;
cin >> s;
bool answer;
if ( answer = ( s == "yes" || s == "Yes" ) )
cout << "Cool" << endl;
else if ( answer = ( s == "no" || s == "No" ) )
cout << "Interesting" << endl;
else
cout << "A simple Yes or No will suffice..." << endl;
} while ( !answer );
system( "pause" );
return 0;
}

if you want to accept "yes" or "Yes" you should write condition like this:
if (i=="yes" || i=="Yes")
But better solution is make string's letters same case (lower or upper) and then compare it.

int main ()
{
go:
string i;
while(1)
{
cout << "Are you Human?>"<<endl;
cin >> i;
if (i == "yes"|| i == "Yes")
cout<< "Cool"<<endl;
else if (i == "no"|| i == "No")
cout<< "Interesting"<<endl;
else
{
cout<< "A simple Yes or No will suffice..."<<endl;
break;
}
}
system("pause");
return 0;
}
Don't forget that if you don't put curly braces after the statements, only the following statement is to be executed.

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!

What does it mean by "error: not declared in this scope?" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include <iostream>
#include <string>
using namespace std;
int main ()
{
do
{
string name, answer;
cout << "Welcome to the prime number checker! Please enter your name: ";
getline (cin, name);
int a;
cout << "\nHello " << name;
cout << "\nPlease enter an integer: ";
cin >> a;
cin.sync();
if (a == 2)
{
cout << "\nThis is a prime number" << endl;
}
else
{
for (int b = 2; b < a; b++)
{
if (a % b == 0)
{
cout << "This number is not prime number" << endl;
break;
}
else
{
cout << "This number is a prime number." << endl;
break;
}
}
}
cout << "Do you want to do this again (Yes or No)?";
getline (cin, answer);
}
while (answer == "yes" || answer == "YES" || answer == "Yes"); //Not declared in this scope
return 0;
}
You declared answer within the do block. But then try to reference answer outside of that scope block.
Declare answer at the top of main instead of in the do block.
You need to move the declaration of answer outside the loop:
string answer;
do {
string name;
...
} while (answer == "yes" || answer == "YES" || answer == "Yes");
If you declare it inside the loop, it no longer exists by the time the while clause is evaluated.
As other people said, the "answer" variable only exists inside the loop - it isn't accessible from outside it.
One other recommendation: rather than checking every possible permutation of capitalization just cast the whole string to lowercase. (You actually missed several - there are 6 total because each position could have one of 2 possible values. Presumably something like "YeS", for example, should still be accepted as "yes").

How do I get out of this do-while loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to create a program that intakes a string of characters, verifies it, then sorts it and prints it out.
I'm sure there is a glaring logic error in here somewhere, can someone help point it out? I've spent hours staring at my screen. I tried everything I know in my limited knowledge of C++, but I still can't get the thing working.
Anything you can offer will help me in some way, even if it's condescending.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void mySort(string &s);
int main()
{
string str;
char c;
bool invalid = true;
cout<<"Please enter some alphabetical characters:"<<endl;
cout<<"(* to end input): ";
do
{
getline(cin, str, '*');
for(int i = 0; i < str.length(); i++)
{
c = str.at(i);
}
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
{
cout<<"Error!"<<endl;
}
else
{
(invalid==false);
cout<<"You entered: "<<str<<endl;
mySort(str);
}
} while(invalid==true);
system("PAUSE");
return(0);
}
void mySort(string &s)
{
sort(s.begin(), s.end());
cout<<"The string after sorting is: "<<s<<endl;
}
I'm almost sure the problem with the verification lies in this line:
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
I'm sure my bools are wrong as well.
Anything, anything at all, I've wasted several hours of my life banging my head against the wall because of this.
You never set invalid to anything but true.
This line:
(invalid==false);
should be:
invalid = false;
The former version compares invalid to false, then throws away the result of the comparison. Nothing changes.
(invalid==false); Should be invalid=false;
First change:
(invalid == false);
invalid = false;
As others have said, you are not assigning the invalid variable correctly. You are also not validating the input string correctly, either. You loop through the entire string, and then validate only the last character seen, rather than validating each character while looping.
I would suggest re-writing the loop to get rid of the invalid variable and fix the validation, eg:
int main()
{
string str;
char c;
do
{
cout << "Please enter some alphabetical characters:" << endl;
cout << "(* to end input): ";
if (!getline(cin, str, '*'))
break;
if (str.empty())
cout << "You did not enter anything!" << endl;
else if (str.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != string::npos)
cout << "Error! Bad input" << endl;
else
{
cout << "You entered: " << str << endl;
mySort(str);
break;
}
}
}
while (true);
system("PAUSE");
return 0;
}

Refine my code/program where did I go wrong?

#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

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{}