1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
#include <iostream> #include <vector> #include <string> #include <iomanip> class Spreadsheet { private: std::vector<std::vector<std::string>> data; size_t rows, cols; public: Spreadsheet(size_t r, size_t c) : rows(r), cols(c) { data.resize(rows, std::vector<std::string>(cols, "")); } void setValue(size_t row, size_t col, const std::string& value) { if (row < rows && col < cols) { data[row][col] = value; } else { std::cerr << "Invalid cell coordinates!" << std::endl; } } std::string getValue(size_t row, size_t col) const { if (row < rows && col < cols) { return data[row][col]; } else { std::cerr << "Invalid cell coordinates!" << std::endl; return ""; } } void display() const { for (const auto& row : data) { for (const auto& cell : row) { std::cout << std::setw(10) << cell << " "; } std::cout << std::endl; } } }; int main() { size_t rows, cols; std::cout << "Enter the number of rows and columns: "; std::cin >> rows >> cols; Spreadsheet sheet(rows, cols); while (true) { std::cout << "\n1. Set Value\n2. Get Value\n3. Display\n4. Exit\n"; int choice; std::cin >> choice; if (choice == 1) { size_t r, c; std::string value; std::cout << "Enter row, column, and value: "; std::cin >> r >> c >> value; sheet.setValue(r, c, value); } else if (choice == 2) { size_t r, c; std::cout << "Enter row and column: "; std::cin >> r >> c; std::cout << "Value at (" << r << ", " << c << ") is " << sheet.getValue(r, c) << std::endl; } else if (choice == 3) { sheet.display(); } else if (choice == 4) { break; } else { std::cout << "Invalid choice!" << std::endl; } } return 0; } |
Explanation
- Class Definition:
Spreadsheet
class is used to manage a 2D grid of cells.- It has private members
data
(a 2D vector of strings) to store cell values, androws
,cols
to store the dimensions of the spreadsheet.
- Constructor:
- Initializes the
data
vector with empty strings and sets the dimensions.
- Initializes the
- Member Functions:
setValue(size_t row, size_t col, const std::string& value)
: Sets the value at the specified cell if coordinates are valid.getValue(size_t row, size_t col) const
: Retrieves the value from the specified cell if coordinates are valid.display() const
: Displays the entire spreadsheet with each cell formatted to a fixed width.
- Main Function:
- Takes user input to create the spreadsheet with specified dimensions.
- Provides a menu to set values, get values, display the spreadsheet, or exit.
- Handles user interactions through a loop and processes choices accordingly.