UART Baud Rate Validation

#include <iostream>

class UARTDriver {
public:
    // TODO: This member must not be publicly writable.
    // TODO: Only allow discrete hardware-supported baud rates.
    int baud_rate;

    UARTDriver() : baud_rate(9600) {}
    void setBaudRate(int baud){
        // if(baud == 9600 || baud == 19200 || baud == 115200){
        //     baud_rate = baud;
        // }
        switch(baud){
            case 9600:
            case 19200:
            case 115200:
                baud_rate = baud;
                break;
            default:
                break;
        }
    }

    int getBaud() const{
        return baud_rate;
    }
    // TODO: Add a validating setter.
    // TODO: Add read-only access to the current baud rate.
};

int main() {
    int N;
    if (!(std::cin >> N)) return 0;

    UARTDriver driver;

    for (int i = 0; i < N; ++i) {
        int req;
        std::cin >> req;

        // TODO: Replace direct access with a validating API.
        driver.setBaudRate(req);

        std::cout << "Active: " << driver.getBaud() << std::endl;
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

4 115200 500 19200 -1

Expected Output

Active: 115200 Active: 115200 Active: 19200 Active: 19200