Why does this loop back after pressing "N"?

I simply want to know why pressing n, reverts it back to start, and maybe a possible fix for it. (I'm extremely new to this)

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
#include <iostream>

using namespace std;

int main()

{

char choice;

do {
    
    cout << "Main Menu" << endl;
	cout << "What would you like to read about?" << endl;
	cout << "1. Programming Paradigms" << endl;
	cout << "2. Different Programming languages, and their uses" << endl;
	cout << "3. Different C++ Features and their uses" << endl;


	char choice;
	cin >> choice;
	

    
    if (choice=='1') {
		cout << "INFO" << endl;	
	} else if (choice=='2') {
		cout << "INFO" << endl;
	} else if (choice=='3') {
		cout << "INFO" << endl;
	} else {
	    

    }

 
    cout << "Do you want to read up on another topic? (y/n)" << endl;

    cin >> choice;


}
 
 
    while (choice != 'n');

    return 0;

}
You are declaring the variable choice, twice (Line 9 and Line 20). You do not need to declare the variable on line 20. In other words, delete char choice on line 20.

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
#include <iostream>

using namespace std;

int main()

{

char choice;

do {
    
    cout << "Main Menu" << endl;
	cout << "What would you like to read about?" << endl;
	cout << "1. Programming Paradigms" << endl;
	cout << "2. Different Programming languages, and their uses" << endl;
	cout << "3. Different C++ Features and their uses" << endl;


	//char choice;
	cin >> choice;
	

    
    if (choice=='1') {
		cout << "INFO" << endl;	
	} else if (choice=='2') {
		cout << "INFO" << endl;
	} else if (choice=='3') {
		cout << "INFO" << endl;
	} else {
	    

    }

 
    cout << "Do you want to read up on another topic? (y/n)" << endl;

    cin >> choice;


}
 
 
    while (choice != 'n');

    return 0;

}
Last edited on
You have two variables named choice in your program. One is created on line 20 and is only in scope until you reach the } on line 42. The loop condition on line 45 uses the uninitialized variable that was created on line 9.
Topic archived. No new replies allowed.