You are here:

C++/Do While Loop Problem

Advertisement


Question
hello 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)

Answer
change

 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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.