example4_switch_with_initialization.cpp

 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
#include <iostream>
#include <string>

int main() {
    std::cout << "Enter a fruit name: ";
    std::string fruit;
    std::cin >> fruit;

    switch (int length = fruit.length(); length) {
        case 5:
            std::cout << "The fruit name has 5 letters. Is it 'Apple'?";
            break;
        case 6:
            std::cout << "The fruit name has 6 letters. Is it 'Orange'?";
            break;
        case 7:
            std::cout << "The fruit name has 7 letters. Is it 'Banana'?";
            break;
        default:
            std::cout << "The fruit name has " << length << " letters.";
    }

    std::cout << std::endl;
    return 0;
}
Back to switch