Hello, I really need help. If anyone could, please tell me what I'm doing wrong.

Well, I'm making this program that asks if you're happy. Then if you don't answer yes, it will ask the question again until you do. I thought that it would be fun to have a program that forces you to say yes, like most questions people ask you.

Anyway, the program goes wrong here: It just repeats the question over and over again before you can answer it! Please tell me what's wrong.

#include <iostream>

using namespace std;

int main()

{
string dude;
bool repeatit=true;

while (repeatit==true)

cout<< "Are you happy?";
cin>>dude;

if (dude=="yes")
cout<< "Yay!";
repeatit=false;

if (dude=="no")
cout<<"No, you're happy. Try again.";

if (dude!="yes" and dude!="no")
cout<< "Answer in yes or no only.";

system("pause");

}

Please help me!

Learn about scopes.

You have more than 1 line of code 'inside' your while loop, but how does the compiler know which code is inside the while loop?

You do not tell the compiler how many lines are inside the while loop, so the compiler assumes that there is only 1 line, directly following the while loop. So that is the cout << "something";

To tell the compiler that there are more lines, surround them with brackets ( { and } ) like:

while( expression )
{
    cout << "something";
    cout << "Something else";
}

This will print "something" and "something else" in a while loop. Without the brackets it would only print "something"

Edited 7 Years Ago by thelamb: n/a

Due to your bad formatting, you can't even tell that it's entering an infinite loop on line 10.
Here's your corrected code.

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string dude;
  bool repeatit=true;

  while (repeatit == true) {
    cout << "Are you happy?\n";
    cin >> dude;

    if (dude == "yes") {
      cout << "\nYay!";
      repeatit = false;
    }

    if (dude == "no") {
      cout<<"\nNo, you're happy. Try again.\n";
    }

    if (dude != "yes" && dude != "no") {
      cout<< "\nAnswer in yes or no only.\n";
    }
  }

  cin.ignore();
  cin.ignore();
}

Hope this helps.

Edited 7 Years Ago by William Hemsworth: n/a

This question has already been answered. Start a new discussion instead.