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

C++新手求教:如何读取.txt文件并使用自定义QuickSort排序?

How to Read Data from a .txt File and Sort It with Your QuickSort Function

Hey there! Since you're a programming newbie, I'll keep this as straightforward as possible. Let's walk through how to modify your existing code to read numbers from a text file, sort them using your QuickSort function, and even print the sorted results.

First, let's fix a small missing piece in your code: the Swap function. Your QuickSort calls it, but it's not defined yet. Here's a simple implementation that works with your existing logic:

void Swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Step 1: Prepare Your Text File

First, create a .txt file (let's call it numbers.txt) with your input numbers. You can write them either space-separated or each on a new line—we'll use space-separated in this example, like:

2 4 3 2 6 7 5

Step 2: Code to Read the File

We'll use standard C file functions (fopen, fscanf, fclose) to read the numbers. Here's the breakdown:

  1. Open the file for reading and handle cases where the file can't be found.
  2. Count how many numbers are in the file so we know how big our array needs to be.
  3. Allocate memory for the array (or use a fixed-size array if you know the number of elements in advance).
  4. Read the numbers into the array.

Step 3: Integrate with QuickSort and Output Results

Once we have the array loaded with numbers from the file, we can call your QuickSort function, then print the sorted array to verify the result.

Complete Working Code

Here's the full code that ties everything together:

#include <stdio.h>
#include <stdlib.h> // For malloc/free

// Swap function required by QuickSort
void Swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Your existing QuickSort function (updated to use pointer-based Swap)
void QuickSort(int A[], int left, int right) {
    int x = A[(left + right)/2];
    int i = left, j = right;
    do {
        while (A[i] < x) i++;
        while (A[j] > x) j--;
        if (i <= j) {
            Swap(&A[i], &A[j]); // Pass addresses to modify original values
            i++;
            j--;
        }
    } while (i < j);
    if (left < j) QuickSort(A, left, j);
    if (i < right) QuickSort(A, i, right);
}

int main() {
    // Open the text file for reading
    FILE *file = fopen("numbers.txt", "r");
    if (!file) { // Check if file opened successfully
        printf("Error: Could not open numbers.txt!\n");
        return 1;
    }

    // First pass: count how many numbers are in the file
    int count = 0;
    int num;
    while (fscanf(file, "%d", &num) == 1) {
        count++;
    }

    // Reset file pointer to the start of the file
    rewind(file);

    // Allocate memory for the array (exact size needed)
    int *arr = (int *)malloc(count * sizeof(int));
    if (!arr) {
        printf("Error: Could not allocate memory for the array!\n");
        fclose(file);
        return 1;
    }

    // Second pass: read numbers into the array
    int i;
    for (i = 0; i < count; i++) {
        fscanf(file, "%d", &arr[i]);
    }

    // Close the file since we're done reading from it
    fclose(file);

    // Sort the array using your QuickSort function
    QuickSort(arr, 0, count - 1);

    // Print the sorted results
    printf("Sorted numbers:\n");
    for (i = 0; i < count; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Free the allocated memory to avoid memory leaks
    free(arr);

    return 0;
}

Key Notes for Newbies:

  • File Path: Make sure numbers.txt is in the same folder as your program, or use the full path (like C:/Users/YourName/Documents/numbers.txt on Windows).
  • Pointer Swap: I updated the Swap call to pass addresses (&A[i], &A[j]) because in C, functions can't modify variables directly unless you pass their memory addresses.
  • Memory Management: Using malloc lets us create an array that's exactly the size we need instead of guessing a fixed size. Always remember to free the memory when you're done with it!
  • Error Checking: We added checks for file opening and memory allocation—this helps you debug common issues like missing files or insufficient memory.

How to Run:

  1. Save the code as quicksort_file.c.
  2. Create numbers.txt with your input numbers.
  3. Compile with a C compiler (like GCC: gcc quicksort_file.c -o quicksort_file).
  4. Run the executable (./quicksort_file on Linux/macOS, quicksort_file.exe on Windows).

That's it! This should work smoothly for your needs. If you run into any tiny hiccups, just double-check the file path or make sure your text file has valid numbers. Happy coding!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:47:25