0

我想知道是否有任何简单的方法可以直接“跳转”到特定案例。

我知道这可以通过使用 do while 循环来完成。想知道是否有更优雅的方式。

例如(当然不是整个代码):

.
.
.
case 8:
            {
                if (grades.findStudent(tempid1)==-1)
                {
                    cout << "\nOne of the ID's you have entered wasn't found. Try again.\n" << endl;
                    case(8); //<- <- <- something like that
                }

            }
            break;
.
.
.
4

5 回答 5

2

当然。做:

switch (...) {
    case 1:
        foo ();
        goto bar;
    case 2:
        ...

    bar:
    case 42:
        baz ();
        break;
}

但是您的问题可能存在其他解决方案。

于 2013-04-12T18:43:18.833 回答
1

唔...

我认为重组它的#1 最佳方法是制作函数中的任何内容,然后简单地在你想使用它的地方和其他地方case 8:调用该函数。case 8:

于 2013-04-12T19:04:27.127 回答
0

你在这里有错误的控制结构。你想要这样的东西:

int studentId;
while(true) {
    studentId = getStudentId();  // Sorry, I'm rusty.
    if (isValid(studentId)) { break;}
}
switch (...) {
    ...
}

一次做一件事。你不是达夫设备的达夫。看那个。好吓人!

于 2013-04-12T18:48:08.733 回答
0

也许这会更好

case 8:
   while (grades.findStudent(tempid1)==-1)
   {
      cout << "\nOne of the ID's you have entered wasn't found. Try again.\n" << endl;
      // Do whatever to enter tempid1 (perhaps a function here that is used
      // before the start of this switch statement?
   }
于 2013-04-12T18:49:30.830 回答
0

我不知道,但我怀疑这是某种“菜单系统”,而 8 是“搜索学生”。

在这种情况下,您要执行以下操作:

            while (grades.findStudent(tempid1)==-1)
            {
                cout << "\none of the ID's you have entered wasn't found. Try again.\n" << endl;
                // add code to ask for tempid1 again
            }

所以,不要使用“if”,而是使用“while”。

于 2013-04-12T18:52:51.197 回答