Each hospital should have the same number of masks and gowns. Write a C++ program that reads all the data from the file and displays each hospital with the number of items that are needed to make the two numbers the same.
时间: 2024-01-03 15:05:51 浏览: 31
Here's an example program that reads the data from the "equipment.txt" file and displays each hospital with the number of items needed to make the number of masks and gowns the same:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ifstream file("equipment.txt");
string line;
// Read each line of the file
while (getline(file, line)) {
stringstream ss(line);
string hospital;
int masks, gowns;
// Parse the line into hospital name, number of masks, and number of gowns
getline(ss, hospital, ';');
ss >> masks;
ss.ignore();
ss >> gowns;
// Calculate the number of items needed to make masks and gowns the same
int diff = abs(masks - gowns);
int total = masks + gowns;
int needed = total / 2 - min(masks, gowns);
// Display the results
cout << hospital << ": Needs " << needed << " more of ";
if (masks < gowns) {
cout << "masks\n";
} else {
cout << "gowns\n";
}
}
// Close the file
file.close();
return 0;
}
```
In this program, we first create an object of the `ifstream` class named "file" and pass the name of the file we want to read from as an argument to the constructor.
Then, we read each line of the file using the `getline()` function and parse it into the hospital name, number of masks, and number of gowns using a `stringstream`.
Next, we calculate the number of items needed to make masks and gowns the same by finding the absolute difference between the two and dividing the total by 2, then subtracting the lower number of masks or gowns.
Finally, we display the results by printing the hospital name and the number of items needed to make the two numbers the same, along with whether more masks or gowns are needed.
Note that we use the `abs()` function to ensure that the difference between masks and gowns is always positive, regardless of which number is greater.