You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fgets读取整数文本后,如何正确提取多位数到int数组?

Fixing Your String-to-Integer Array Conversion Issue

Let's walk through what's going wrong and how to fix it step by step:

Key Problems in Your Code

  1. Duplicate/Incorrect Integer Parsing
    When you call atoi(&str[i]) on a multi-digit number (like "17"), atoi reads all consecutive digits starting at i to form the full integer. But your current code only increments i by 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 your intArray.

  2. Wrong Count for printArray
    You're passing intArray[0] as the element count to printArray, but that's the value of the first integer in your file—not how many integers you actually parsed. You should use the j variable, which tracks the number of elements added to intArray.

  3. Minor Bug in fileSize
    The getc function returns an int (to properly represent EOF, which is outside the range of char). Using char c here 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 fopen didn'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:52:40