从txt文件读取输入并构建动态二维数组的C语言技术求助
Hey there! As a fellow C learner who's been in your shoes, let's work through this problem together. The goal is to read lines from input.txt (each with 2 strings and 2 numbers) into a dynamically allocated array—perfect use case for malloc and structs since we don't know the number of lines upfront.
Step 1: Create a Struct to Store Each Line's Data
Since each line has mixed data types (strings and numbers), using a struct is the cleanest way to group them together. This makes our dynamic array an array of structs, which is far easier to manage than a messy multi-type 2D array.
#include <stdio.h> #include <stdlib.h> #include <string.h> // Define a struct to hold one line's data typedef struct { char str1[50]; // Adjust size based on your string needs char str2[50]; int num1; int num2; } LineData;
Note: I set the string buffers to 50 characters—you can increase this if your input strings are longer. If you need truly dynamic strings, we could add malloc for the strings too, but let's start simple for now.
Step 2: Dynamically Allocate the Array
We'll start with an initial size for our array, then use realloc to expand it if we need more space as we read lines. This handles cases where we don't know the exact number of lines in advance.
int main() { FILE *file = fopen("input.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } // Initial array size (we can expand this later) int capacity = 10; LineData *data_array = malloc(capacity * sizeof(LineData)); if (data_array == NULL) { perror("Failed to allocate memory"); fclose(file); return 1; } int line_count = 0; LineData current_line;
Step 3: Read the File Line by Line
We'll use fscanf to read each line's data, since the format is fixed (2 strings followed by 2 integers). Every time we fill up our current array capacity, we'll use realloc to double the size (a common strategy for dynamic arrays).
// Read until end of file while (fscanf(file, "%s %s %d %d", current_line.str1, current_line.str2, ¤t_line.num1, ¤t_line.num2) == 4) { // Check if we need to expand the array if (line_count >= capacity) { capacity *= 2; LineData *temp = realloc(data_array, capacity * sizeof(LineData)); if (temp == NULL) { perror("Failed to reallocate memory"); free(data_array); fclose(file); return 1; } data_array = temp; } // Copy the current line into the array data_array[line_count] = current_line; line_count++; }
Step 4: Use the Data (Example)
Let's print out what we read to verify it works:
// Print the stored data printf("Read %d lines:\n", line_count); for (int i = 0; i < line_count; i++) { printf("Line %d: %s %s %d %d\n", i+1, data_array[i].str1, data_array[i].str2, data_array[i].num1, data_array[i].num2); }
Step 5: Clean Up Memory
Always free the memory you allocated and close the file to avoid leaks!
// Cleanup free(data_array); fclose(file); return 0; }
Key Notes for Beginners
- Error Checking: I added checks for
fopen,malloc, andreallocfailures—this is crucial in C, ignoring these can lead to crashes or weird behavior. - Structs: Using a struct keeps related data together, making your code easier to read and maintain.
- Realloc Strategy: Doubling the capacity each time is efficient because it minimizes how often we need to reallocate memory.
- String Sizes: If your input strings are longer than 50 characters, increase the buffer size in the struct, or hit me up if you want to learn dynamic string allocation!
Example input.txt
If you use this test file:
apple banana 10 20 cat dog 30 40 elephant fox 50 60
The program will output:
Read 3 lines: Line 1: apple banana 10 20 Line 2: cat dog 30 40 Line 3: elephant fox 50 60
内容的提问来源于stack exchange,提问作者gokhan_ozeloglu




