How to fix transfer of control bypass initialization of error?

I am creating a program where you input different data for pets. It uses a menu system with switch statements. However upon compiling I get the transfer of control error. How can I fix 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main()

{
	int user_choice;

	cout << "\nManage Your Pet\n"
		<< "  1. Create Pet\n"
		<< "  2. Display Pet\n"
		<< "  3. Delete Pet\n"
		<< "  4. Exit\n"
		<< "\nEnter your choice (1-4): ";
	cin >> user_choice;
	cout << endl;

	switch (user_choice)
	{
		string pname;
		string ptype;
		int page;
		string pcomment;

	case 1:

		ofstream fw("pet.txt", std::ofstream::out);

		if (fw.is_open())
		{
			cout << "What is your pet's name?" << endl;
			cin >> pname;
			fw << pname << '\n';
			cout << "What is your pet's type?" << endl;
			cin >> ptype;
			fw << ptype << '\n';
			cout << "How old is your pet?" << endl;
			cin >> page;
			fw << page << '\n';
			cout << "Enter a comment about the pet!" << endl;
			cin >> pcomment;
			fw << pcomment << '\n';
			cout << "Data stored!" << endl;
			fw.close();
		}
		else cout << "Problem with opening file";
		break;

	case 2:

		string myText;

		ifstream MyReadFile("pet.txt");

		cout << "What is your pet's name?" << endl;
		cin >> pname;

		while (getline(MyReadFile, myText))
		{
			cout << myText;
		}

		MyReadFile.close();
		break;

	case 3:

		string find;
		string line;

		cout << "Pet Name? " << endl;
		cin >> find;

		ifstream myfile2;
		myfile2.open("pet.txt");

		ofstream temp;
		temp.open("temp.txt");
		while (getline(myfile2, line))
		{
			if (line != find)
				temp << line << endl;
		}
		myfile2.close();
		temp.close();
		remove("pet.txt");
		rename("temp.txt", "pet.txt");
		break;

	case 4:
		cout << "Good-bye." << endl;
		break;

	default:
		cout << "We're sorry. \nYour choice must "
			<< "between 1 and 4.\n"
			<< "Rerun the program and try again."
			<< endl;
		break;
	}

	cout << endl;

	return 0;
}
Please post the complete text of the error.
Code E0546 transfer of control bypasses initialization of:
1
2
3
4
5
6
7
8
switch (user_choice)
	{
		string pname;
		string ptype;
		int page;
		string pcomment;

	case 1:

Which case do these variables belong to?


You might need to write each case as
1
2
3
4
5
6
case 1:
{ // add braces around the body of each case.
    // vars
    // statements
    break;
}
You can't define variables in the body of a case statement unless they are within a {} block. You also can't have statements outside of a case.
Topic archived. No new replies allowed.