关于锯齿数组(Jagged Arrays)的文件读写技术咨询
Hey there! Let's tackle your jagged array file writing problem step by step, since you're sticking to raw pointers instead of vectors for now. First, let's make sure we're on the same page: you've got a class that reads data from a TXT file using inputF >> rowIndex >> temp..., and you need to implement the empty writeJaggedArrayToFile function to output the converted data.
Key Prerequisites Before Writing
First, you need to track two critical pieces of information for your jagged array (since each row can have a different length):
- The total number of rows in your jagged array.
- An array that stores the number of elements in each individual row (let's call this
rowSizes). You must populate this while reading your input file—otherwise, you won't know how many elements to write per row.
Implementing writeJaggedArrayToFile
Here's a straightforward implementation that matches the input format you're using (row index followed by elements). We'll use raw pointers and standard file streams, no vectors involved:
#include <fstream> #include <iostream> #include <limits> void writeJaggedArrayToFile(const char* outputFilename, int** jaggedArray, int* rowSizes, int totalRows) { // Open the output file in write mode std::ofstream outputFile(outputFilename); if (!outputFile.is_open()) { std::cerr << "Failed to open output file for writing!" << std::endl; return; } // Iterate over each row for (int row = 0; row < totalRows; ++row) { // First write the row index (matching your input format) outputFile << row << " "; // Write all elements in the current row for (int col = 0; col < rowSizes[row]; ++col) { outputFile << jaggedArray[row][col]; // Add a space between elements (skip after the last one) if (col != rowSizes[row] - 1) { outputFile << " "; } } // New line after each row outputFile << std::endl; } // Always close the file when done outputFile.close(); }
Quick Notes on Your Reading Logic
Since you're using inputF >> rowIndex >> temp..., let's make sure your reading code correctly builds the jagged array and populates rowSizes. Here's a snippet to complement your existing code (no vectors, just raw pointers):
// Initialize your jagged array and row size tracker int** jaggedArray = nullptr; int* rowSizes = nullptr; int maxRowIndex = -1; int tempValue; int currentRow; std::ifstream inputFile("input.txt"); if (!inputFile.is_open()) { std::cerr << "Failed to open input file!" << std::endl; return; } // First pass: Find the maximum row index to allocate enough space while (inputFile >> currentRow) { // Skip elements for this pass, just track the highest row number while (inputFile.peek() != '\n' && inputFile.peek() != EOF) { inputFile >> tempValue; } inputFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (currentRow > maxRowIndex) { maxRowIndex = currentRow; } } // Reset file to read again from the start inputFile.clear(); inputFile.seekg(0, std::ios::beg); // Allocate memory for jagged array and row sizes int totalRows = maxRowIndex + 1; jaggedArray = new int*[totalRows]; rowSizes = new int[totalRows](); // Initialize all to 0 // Second pass: Populate the jagged array while (inputFile >> currentRow) { int elementCount = 0; int* tempRow = nullptr; int tempCapacity = 2; // Start with small capacity, expand as needed // Allocate initial space for the row tempRow = new int[tempCapacity]; // Read all elements in the current row while (inputFile.peek() != '\n' && inputFile.peek() != EOF) { inputFile >> tempValue; // Expand tempRow if we run out of space if (elementCount >= tempCapacity) { int* newTempRow = new int[tempCapacity * 2]; for (int i = 0; i < elementCount; ++i) { newTempRow[i] = tempRow[i]; } delete[] tempRow; tempRow = newTempRow; tempCapacity *= 2; } tempRow[elementCount++] = tempValue; } inputFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Transfer tempRow data to the jagged array jaggedArray[currentRow] = new int[elementCount]; rowSizes[currentRow] = elementCount; for (int i = 0; i < elementCount; ++i) { jaggedArray[currentRow][i] = tempRow[i]; } // Clean up temporary row memory delete[] tempRow; } inputFile.close(); // Now you can call the write function writeJaggedArrayToFile("output.txt", jaggedArray, rowSizes, totalRows); // Don't forget to free memory to avoid leaks! for (int i = 0; i < totalRows; ++i) { delete[] jaggedArray[i]; } delete[] jaggedArray; delete[] rowSizes;
Critical Reminders
- Memory Management: Since you're using raw pointers, always remember to free the memory you allocate (like the cleanup code at the end of the reading snippet). Forgetting this will cause memory leaks.
- Format Consistency: The write function matches the input format (row index followed by elements). Adjust the separator (spaces, commas, etc.) if your input/output requires a different format.
- Error Handling: The code includes basic file open checks—you can expand this with additional error handling if needed (e.g., invalid row indices in the input file).
内容的提问来源于stack exchange,提问作者Alex Names

