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

C++读取文件数据存入int数组出现异常值的问题求助

Problem Analysis

Key Issues

  • Integer Overflow: The values 2312354234 and 3254132515 exceed the maximum limit of a 32-bit signed integer (INT_MAX = 2147483647). Reading these into an int variable triggers undefined behavior, which in your case set the input stream to a failed state.
  • Uninitialized Array Elements: Once the stream enters a failed state, all subsequent read operations (infile >> arr[i]) do nothing. The remaining array elements retain uninitialized garbage values (like -842150451).

Solution

Step 1: Use a Larger Integer Type

Replace int with long long (a 64-bit integer type) to accommodate the large values in your file. long long can hold numbers up to 9223372036854775807, which is more than sufficient for your data.

Step 2: Add Input Validation

Check if file operations succeed to catch errors early and avoid processing invalid data.

Corrected Code

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream infile("data.txt");
    // Check if file opened successfully
    if (!infile) {
        cerr << "Failed to open data.txt" << endl;
        return 1;
    }

    int sn = 0;
    // Check if reading the element count succeeded
    if (!(infile >> sn)) {
        cerr << "Failed to read the number of elements" << endl;
        return 1;
    }

    // Use long long array to store large values
    long long* arr = new long long[sn];

    for (int i = 0; i < sn; ++i) {
        // Validate each read operation
        if (!(infile >> arr[i])) {
            cerr << "Failed to read element at index " << i << endl;
            delete[] arr; // Cleanup allocated memory
            return 1;
        }
    }

    // Output the array elements
    for (int i = 0; i < sn; ++i) {
        cout << arr[i] << endl;
    }

    // Free allocated memory to avoid leaks
    delete[] arr;
    infile.close();
    return 0;
}

Expected Output

1231234213
12
2312354234
23
3254132515
43

Additional Notes

  • Always validate file operations (opening, reading) to handle cases where the file is missing or corrupted.
  • Remember to deallocate dynamically allocated arrays with delete[] to prevent memory leaks.
  • If you don't need dynamic allocation, consider using a vector<long long> instead, which manages memory automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:10:16