C++/Do While Loop Problem
Expert: vijayan - 4/23/2009
Questionhello expert,
To start off, i'm very new so this could be an easy fix.
I use dev C++. let me just put the code.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string string1="You are right!";
string string2="You are wrong!";
string answer;
do
{
cout<<"What is the is North Carolina's Capital City?"<<endl<<endl;
cin>>answer;
if(answer =="Raleigh" || answer =="raleigh")
{
cout<<string1<<endl;
}
else
{
cout<<string2<<endl;
}
}while(answer !="Raleigh" || answer !="raleigh");
return 0;
}
This runs, however it keeps running even after I enter Raleigh or raleigh. This does the same if I just make it a while() statement. I appreciate any help ;O)
Answerchange
do
{
// .....
} while( answer != "Raleigh" || answer != "raleigh" ) ;
to
do
{
// .....
} while( answer != "Raleigh" && answer != "raleigh" ) ;
and you would be ok.
the reason for the change should be obvious to you; if it is not, make sure that you can reason it out on your own - that is the way you learn.
also, prefer writing fully parenthesized sub-expressions as in:
while( ( answer != "Raleigh" ) && ( answer != "raleigh" ) ) ;
that way, you do not have to keep worrying about operator precedence all the time.