首页 > 解决方案 > 在排除 C++ 的 switch case 中使用范围

问题描述

gcc 中有一个扩展,它允许在 switch case 语句中使用“范围”。

case 'A' ... 'Z':

允许制作一个字符在 A 到 Z 范围内的任何地方的情况。
是否可以在这样的范围语句中进行“排除”?例如,假设我希望我的案例捕获除“G”和“L”之外的所有字符 AZ。

我知道一个简单的解决方案是处理 AZ 案例正文中的特殊字符,但如果存在上述解决方案,我更愿意

标签: c++gcc

解决方案


正如评论者所观察到的,这不是标准的 C++。

我不会在我的代码中使用它。

然而,使用 GCC 的 g++,它可以像这样工作:

#include <iostream>

using namespace std;

int main()
{
    cout << "Case test" << endl;
    for (char c = '0'; c<'z'; c++)
    {
        switch (c)
        {
        case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
            cout << c;
            break;
        default:
            cout << ".";
            break;
        }
    }
}
g++ case.cpp -o case -W -Wall -Wextra -pedantic && ./case

case.cpp: In function ‘int main(int, char**)’:
case.cpp:15:9: warning: range expressions in switch statements are non-standard [-Wpedantic]
         case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
         ^~~~
case.cpp:15:29: warning: range expressions in switch statements are non-standard [-Wpedantic]
         case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
                             ^~~~
case.cpp:15:53: warning: range expressions in switch statements are non-standard [-Wpedantic]
         case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
                                                     ^~~~
Case test
.................ABCDEF.HIJK.MNOPQRSTUVWXYZ...............................

推荐阅读