The while loop in my class won’t close.

I’m writing a program to try and use everything I’ve learned and basically see if I can explain it as well. The only problem is that when it comes to this code:

while(response1 != answer){
cout << "Try again" << endl;
cin >> response1;
}
When I answer wrong it prints out “Try again”, but if I type the correct answer it outputs “Try again” twice. I’m not done with it, but I’m debugging while writing the program. Please help me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  #include <iostream>
#include <string>

using namespace std;

class Chapterone{//The first programming example
	public:
	void mainintro(){
		    return helloWorld();
	}
	void helloWorldre(){
			return d();
	}
		
	private:
	void helloWorld(){//introduction
		cout << "Hello and welcome to our C++ learning app!" << endl;
		}
	void d(){
		string response1;
		string answer = "\"Hello World\"";	
		cout << answer << endl;
		string codeex1;//helloWorld basic program
		codeex1 = "#include <iostream>\n using namespace std;\n \n int main(){\n cout << blank << endl;\n \n return 0;\n }";
		cout << codeex1 << endl;
		cout << "What belongs in the blank?" << endl;
		cin >> response1;
			
		while(response1 != answer){
			cout << "Try again" << endl;
			cin >> response1;
		}
		cout << "Nice job!" << endl;
	}
};


int main(){
	
	string name;
	
	Chapterone chap1Obj;
	chap1Obj.mainintro();
	cout << "What's your name? ";
	cin >> name;
	cout << "Welcome " << name << endl;
	cout << "Let's get started!" << endl;
	cout << " " << endl;
	cout << " " << endl;
	cout << " " << endl;
	
	chap1Obj.helloWorldre();
	cin.get();
	
	return 0;
	}
cin >> is delimited by whitespace, meaning it will only read one word at a time.
Use
getline(cin, response);

And try printing what the result put in response is to give yourself a better idea of what's happening.
Last edited on
Thanks I tried replacing the cin >> with the getline. But right after the program prints “try again” before I input anything.
Topic archived. No new replies allowed.