UART Baud Rate Validation

#include <iostream>

class UARTDriver {
private: 
    int baud_rate; 

public:
    // TODO: This member must not be publicly writable.
    // TODO: Only allow discrete hardware-supported baud rates.

    UARTDriver() : baud_rate(9600) {}

    // TODO: Add a validating setter.
    // TODO: Add read-only access to the current baud rate.

    void setBaudRate (int req) {
        switch (req) {
            case 9600: 
            case 19200: 
            case 115200: 
                baud_rate = req; 
                break;
            default: 
                break; 
        }
    }

    int getBaudRate() const {
        return 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.getBaudRate() << 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