温馨提示×

c++ tolower在switch中如何运用

c++
小樊
82
2024-06-24 16:39:27
栏目: 编程语言

在C++中,tolower函数用于将一个字符转换为小写字符。在switch语句中,可以使用tolower函数来将输入的字符转换为小写字符,然后根据不同的小写字符进行不同的操作。

例如,假设我们想要根据用户输入的字符来执行不同的操作,可以使用类似如下的代码:

#include <iostream>
#include <cctype>

int main() {
    char input;
    std::cout << "Enter a character: ";
    std::cin >> input;

    char lowercaseInput = tolower(input);

    switch (lowercaseInput) {
        case 'a':
            std::cout << "You entered 'a'" << std::endl;
            break;
        case 'b':
            std::cout << "You entered 'b'" << std::endl;
            break;
        default:
            std::cout << "Invalid input" << std::endl;
            break;
    }

    return 0;
}

在上面的代码中,用户输入一个字符,然后使用tolower函数将字符转换为小写字符。接着在switch语句中根据小写字符的值来执行不同的操作。如果用户输入的字符是’a’,则输出"You entered ‘a’“;如果用户输入的字符是’b’,则输出"You entered ‘b’”;如果用户输入的其他字符,则输出"Invalid input"。

这样就可以根据用户输入的字符来执行不同的操作,同时保证不区分大小写。

0