使用fgets读取整数文本后,如何正确提取多位数到int数组?
Let's walk through what's going wrong and how to fix it step by step:
Key Problems in Your Code
Duplicate/Incorrect Integer Parsing
When you callatoi(&str[i])on a multi-digit number (like "17"),atoireads all consecutive digits starting atito form the full integer. But your current code only incrementsiby 1 after parsing, so the next loop iteration will process the second digit of the number (e.g., the '7' in "17") as a new integer. This leads to duplicate or wrong values in yourintArray.Wrong Count for
printArray
You're passingintArray[0]as the element count toprintArray, but that's the value of the first integer in your file—not how many integers you actually parsed. You should use thejvariable, which tracks the number of elements added tointArray.Minor Bug in
fileSize
Thegetcfunction returns anint(to properly representEOF, which is outside the range ofchar). Usingchar chere can cause incorrect EOF detection in some cases.
Corrected Code
Here's the fixed version with clear explanations in comments:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> typedef struct RATIONAL { int top; int bottom; } RATIONAL; void printArray(int arr[], int count) { for (int i = 0; i < count; ++i) { printf("%d\n", arr[i]); } } int fileSize(FILE* fp) { // Change to int to handle EOF correctly int c; int i = 0; while ((c = getc(fp)) != EOF) { i++; } return i; } int main() { RATIONAL ratArray[23]; // Unused in current code, kept as-is int intArray[45]; FILE* fp = fopen("data.txt", "r"); // Add safety check for file opening failure if (fp == NULL) { printf("Failed to open data.txt!\n"); return 1; } int i = 0, j = 0; int size = fileSize(fp) + 1; char str[size]; rewind(fp); fgets(str, size, fp); // Convert string to array of ints while (i < size - 1) { if (isdigit(str[i])) { intArray[j++] = atoi(&str[i]); // Skip all consecutive digits to avoid re-parsing the same number while (isdigit(str[i])) { i++; } } else { // Skip non-digit characters (like spaces) i++; } } // Use j (actual element count) instead of intArray[0] printArray(intArray, j); // Clean up file handle to prevent resource leaks fclose(fp); return 0; }
Additional Notes
- I added a file opening check—it's always good practice to verify that
fopendidn't fail (e.g., if the file is missing or inaccessible). - The
fclose(fp)call ensures we clean up the file handle, which prevents unnecessary resource usage. - If your file might have more than 45 integers, consider using dynamic memory allocation (
malloc/realloc) instead of a fixed-size array to avoid overflow.
内容的提问来源于stack exchange,提问作者Omar Khaled

