UART Baud Rate Validation

#include <iostream>

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

    UARTDriver() : baud_rate(9600) {};

    void SetBuardRate(int baudRate)
    {
        if ( baudRate == 9600 || baudRate == 19200 || baudRate == 115200 )
            baud_rate = baudRate;
    }

    int GetBaudRate() 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.SetBuardRate(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