Group
Real-Time Programming in C++
Objective
Write a C++ program that simulates a temperature monitoring system. The program should generate random temperature readings at regular intervals. Display the current temperature and trigger an alert if the temperature exceeds a predefined threshold. The user should be able to specify the threshold value.
Develop an application that simulates a real-time temperature monitoring system.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
#include <chrono> // Include the chrono library for time manipulation
#include <thread> // Include the thread library for sleeping functionality
#include <cstdlib> // Include the standard library for random number generation
#include <ctime> // Include the time library for seeding random numbers
using namespace std;
// Function to simulate the temperature monitoring
void monitorTemperature(int threshold) {
srand(time(0)); // Seed the random number generator using the current time
while (true) { // Infinite loop to simulate continuous temperature monitoring
int temperature = rand() % 100; // Generate a random temperature between 0 and 99
cout << "Current Temperature: " << temperature << "°C" << endl;
// Check if the temperature exceeds the threshold
if (temperature > threshold) {
cout << "ALERT! Temperature exceeds threshold!" << endl;
}
// Wait for 2 seconds before generating the next reading
this_thread::sleep_for(chrono::seconds(2));
}
}
int main() {
int threshold;
cout << "Enter the temperature threshold for alert (°C): ";
cin >> threshold; // Get the threshold temperature from the user
// Start the temperature monitoring system with the specified threshold
monitorTemperature(threshold);
return 0;
}
Output
Enter the temperature threshold for alert (°C): 50
Current Temperature: 32°C
Current Temperature: 76°C
ALERT! Temperature exceeds threshold!
Current Temperature: 49°C
Current Temperature: 88°C
ALERT! Temperature exceeds threshold!
Current Temperature: 25°C
...