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

如何在C语言中从文本文件读取整数并分别存储:前两个存独立变量,剩余批量存储

How to Read Specific Integers from a Text File and Store Them Separately in C

Hey there! Let's work through this problem together since you're new to C programming. Right now, your code has a key issue: remaining_num is a single integer variable, which means it can only store one number—so you're only capturing the third value (40) and missing all the rest after that. Let's fix this so you can store all those remaining integers properly.

What's Wrong with the Original Code?

  • remaining_num is declared as a single int, so it can't hold multiple values.
  • You don't check if the file opened successfully (if the user enters a wrong filename, your program will crash).
  • You don't close the file after reading it—while the OS will clean this up when the program ends, it's bad practice to skip this.

Solution 1: Use a Fixed-Size Array (Simple for Beginners)

If you have a rough idea of how many remaining integers there might be (like in your example, there are 8), you can use a fixed-size array to store them. Here's the modified code:

#include<stdio.h>
#include<stdlib.h>

int main() {
    FILE *fp;
    int first_num, second_num;
    // Define an array to hold remaining numbers (we'll assume max 100 to be safe)
    int remaining_num[100];
    int count = 0; // Tracks how many remaining numbers we've stored
    char fileName[100];

    printf("Enter the file name to be read from: ");
    scanf("%s", fileName);

    // Always check if the file opened successfully!
    fp = fopen(fileName, "r");
    if (fp == NULL) {
        printf("Oops! Couldn't open the file. Make sure it exists and the path is correct.\n");
        return 1; // Exit with an error code
    }

    // Read the first two integers
    fscanf(fp, "%d", &first_num);
    fscanf(fp, "%d", &second_num);

    // Loop to read all remaining integers until the end of the file
    while (fscanf(fp, "%d", &remaining_num[count]) == 1) {
        count++;
        // Add a check to avoid overflowing the array
        if (count >= 100) {
            printf("Warning: Too many numbers! The array is full, stopping early.\n");
            break;
        }
    }

    // Print out all our stored values
    printf("First number: %d\n", first_num);
    printf("Second number: %d\n", second_num);
    printf("Remaining numbers: ");
    for (int i = 0; i < count; i++) {
        printf("%d ", remaining_num[i]);
    }
    printf("\n");

    // Don't forget to close the file!
    fclose(fp);
    return 0;
}

Key Notes for This Solution:

  • We use count to keep track of how many numbers we've stored in the array.
  • The while loop runs as long as fscanf successfully reads an integer (it returns 1 when it does).
  • We added a check for array overflow to prevent unexpected behavior if there are more numbers than the array can hold.

Solution 2: Use Dynamic Memory (Flexible for Unknown Numbers)

If you don't know how many remaining integers there will be, dynamic memory allocation is a better choice. This lets us resize the array as needed:

#include<stdio.h>
#include<stdlib.h>

int main() {
    FILE *fp;
    int first_num, second_num;
    int *remaining_num = NULL; // Pointer for dynamic array
    int count = 0;
    int capacity = 2; // Start with a small initial capacity
    char fileName[100];

    printf("Enter the file name to be read from: ");
    scanf("%s", fileName);

    fp = fopen(fileName, "r");
    if (fp == NULL) {
        printf("Oops! Couldn't open the file. Make sure it exists and the path is correct.\n");
        return 1;
    }

    // Read first two integers
    fscanf(fp, "%d", &first_num);
    fscanf(fp, "%d", &second_num);

    // Allocate initial memory for the dynamic array
    remaining_num = malloc(capacity * sizeof(int));
    if (remaining_num == NULL) {
        printf("Error: Couldn't allocate memory!\n");
        fclose(fp);
        return 1;
    }

    int current_num;
    // Read remaining numbers, resizing the array if needed
    while (fscanf(fp, "%d", &current_num) == 1) {
        if (count >= capacity) {
            // Double the capacity when we run out of space
            capacity *= 2;
            int *temp = realloc(remaining_num, capacity * sizeof(int));
            if (temp == NULL) {
                printf("Error: Couldn't resize memory!\n");
                free(remaining_num);
                fclose(fp);
                return 1;
            }
            remaining_num = temp;
        }
        remaining_num[count++] = current_num;
    }

    // Print results
    printf("First number: %d\n", first_num);
    printf("Second number: %d\n", second_num);
    printf("Remaining numbers: ");
    for (int i = 0; i < count; i++) {
        printf("%d ", remaining_num[i]);
    }
    printf("\n");

    // Clean up: free dynamic memory and close the file
    free(remaining_num);
    fclose(fp);
    return 0;
}

Key Notes for This Solution:

  • malloc allocates initial memory, and realloc resizes it when we need more space.
  • We always check if memory allocation succeeds (since it can fail on low-memory systems).
  • We must free the dynamic memory at the end to avoid memory leaks.

内容的提问来源于stack exchange,提问作者stocker_619

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:32:40