"Go to case" error when using vectors inside a switch statement.

This is the code where I get a few errors when I add another case or default. I cannot find the main error, for example, a missed semicolon or so, and the code works correctly when I have only one case. I was looking for switch switcher hints, but I didn't find anything about vectors, and mixed switches are the problem.

int main() { int r; while (cin >> r) { switch (r) { case 3: int y = 0; cout << "Please enter some numbers, and I will put them in order." << endl; vector<int> nums; int x; while(cin >> x) { nums.push_back(x); y++; } sort(nums.begin(), nums.end()); int z = 0; while(z < y) { cout << nums[z] << ", "; z++; if(z > 23) cout << "\n" << "User... What ru doin... User... STAHP!" << endl; } cout << "\n" << "You entered "<< nums.size() << " numbers." << endl; cout << "Here you go!" << endl; break; //In the following line I get the "jump to case label" error. //I use Dev C++ software. case 4: cout << "it works!!!" << endl; break; } } system ("PAUSE"); return 0; } 

What am I missing?

+4
source share
1 answer

Add another object inside the enclosure:

 switch(n) { case 1: { std::vector<int> foo; // ... break; } case 2: // ... default: // ... } 

An additional constraint area limits the lifetime of the vector object. Without it, the transition to case 2 skip the initialization of the object, which, however, must be destroyed later, and this is illegal.

+13
source

Source: https://habr.com/ru/post/1499665/


All Articles