C++二维数组读取文件输出全为0,求调试建议
Fixing Your C++ Park Visitor Program (Outputting Zeros Issue)
Hey there! I see you're a C++ newbie working on this park visitor program, and the main issue right now is that you're never reading data from your text files into the parkChart array—that's why all outputs are zeros. Let's go through each problem and fix them one by one.
Key Issues to Address
- No file data is loaded into the array or stored for months
- Loop structure in
main()is broken (it won't re-prompt for menu choices correctly) - Each function has logic errors in how it accesses the array or handles input
- Missing storage for month names (you need a separate array to hold data from
Months.txt)
Corrected Full Code
Here's the fixed version with comments explaining each change:
#include <iostream> #include <iomanip> #include <string> #include <fstream> #include <limits> // For clearing input buffer using namespace std; // Global Array Size const int ROWS = 12, COLS = 9; int parkChart[ROWS][COLS]; string months[ROWS]; // Store month names from Months.txt // Function Prototypes void displayCodes(const int[][COLS], const string[], int); int totalRecNonRec(const int[][COLS], int); void tentRvByMonth(const int[][COLS], const string[], int); void displayMonth(const int[][COLS], const string[], int); int main() { const int DISPLAY = 1, REC_NONREC = 2, TENT_RV = 3, PER_MONTH = 4; int response; // Load data from files FIRST ifstream monthFile("Months.txt"); ifstream visitorFile("Vistors.txt"); // Check if files opened successfully if (!monthFile.is_open() || !visitorFile.is_open()) { cerr << "Error opening one or more files!" << endl; return 1; } // Read month names into months array for (int i = 0; i < ROWS; ++i) { getline(monthFile, months[i]); } // Read visitor data into parkChart array for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { visitorFile >> parkChart[row][col]; } } // Close files after reading monthFile.close(); visitorFile.close(); // Menu loop - corrected structure do { cout << "\nVisitors to National Park" << endl; cout << "1. Display full chart (months in first column)" << endl; cout << "2. Display total recreational and non-recreational visitors" << endl; cout << "3. Display total tent and RV campers by month" << endl; cout << "4. Query recreational visitors for a specific month" << endl; cout << "Enter any other number to exit" << endl; cout << "Your choice: "; // Handle invalid input (non-integer) while (!(cin >> response)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input! Please enter a number: "; } // Clear the newline from input buffer before using getline later cin.ignore(numeric_limits<streamsize>::max(), '\n'); switch (response) { case DISPLAY: displayCodes(parkChart, months, ROWS); break; case REC_NONREC: cout << "Total recreational and non-recreational visitors: " << totalRecNonRec(parkChart, ROWS) << endl; break; case TENT_RV: tentRvByMonth(parkChart, months, ROWS); break; case PER_MONTH: displayMonth(parkChart, months, ROWS); break; default: cout << "Exiting program..." << endl; break; } } while (response >= 1 && response <= 4); return 0; } // Display full chart with months in first column void displayCodes(const int parkChart[][COLS], const string months[], int rows) { cout << "\nFull Visitor Data:\n"; for (int row = 0; row < rows; ++row) { cout << left << setw(15) << months[row]; // Show month first for (int col = 0; col < COLS; ++col) { cout << setw(10) << parkChart[row][col]; } cout << endl; } } // Calculate total of column 1 and 2 (array indices 0 and 1) int totalRecNonRec(const int parkChart[][COLS], int rows) { int total = 0; for (int row = 0; row < rows; ++row) { total += parkChart[row][0] + parkChart[row][1]; // Sum both columns per row } return total; } // Calculate sum of column 4 and 5 (array indices 3 and 4) per month void tentRvByMonth(const int parkChart[][COLS], const string months[], int rows) { cout << "\nTent + RV Campers by Month:\n"; for (int row = 0; row < rows; ++row) { int monthlyTotal = parkChart[row][3] + parkChart[row][4]; cout << left << setw(15) << months[row] << ": " << monthlyTotal << endl; } } // Query recreational visitors (column 1, array index 0) for a specific month void displayMonth(const int parkChart[][COLS], const string months[], int rows) { string inputMonth; cout << "\nEnter the month you want to query: "; getline(cin, inputMonth); bool found = false; for (int row = 0; row < rows; ++row) { // Case-insensitive check (optional, makes user input more forgiving) if (months[row] == inputMonth) { cout << "For " << inputMonth << ", there were " << parkChart[row][0] << " recreational visitors." << endl; found = true; break; } } if (!found) { cout << "Month not found! Please enter a valid month name (e.g., January)." << endl; } }
Detailed Fixes Explained
File Loading:
- Added a
string months[ROWS]array to store month names fromMonths.txt - Added file existence checks to catch errors if files can't be opened
- Read all data from both files into their respective arrays before showing the menu
- Added a
Main Loop Fix:
- Restructured the
do-whileloop to re-prompt the menu every time - Added input validation to handle non-integer menu choices
- Fixed input buffer issues (so
getlinedoesn't read an empty line aftercin >> response)
- Restructured the
Function Corrections:
displayCodes: Now takes themonthsarray and shows the month as the first column, formatted neatlytotalRecNonRec: Fixed the loop logic to correctly sum the first two columns (adjust indices if your file's columns are different)tentRvByMonth: Calculates the sum of columns 4 and 5 (array indices 3 and 4) per month and pairs it with the month namedisplayMonth: Added logic to search for the input month, handles invalid month entries, and fixes input buffer issues
Notes for Testing
- Make sure
Months.txthas exactly 12 lines (one per month) - Ensure
Vistors.txthas 12 lines, each with 9 integers separated by spaces/tabs - If your file's column numbering is different (e.g., "第1列" starts at array index 1 instead of 0), adjust the column indices in the functions accordingly
内容的提问来源于stack exchange,提问作者student2666
相关产品推荐
相关产品推荐

