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

从文本文件读取字符串并排序写入新文件的技术问题

问题:TXT文件提取行并排序写入新文件的代码故障

需求

实现从一个.txt文件提取相关行并排序后写入另一个文件,无特定排序算法要求。

当前问题

代码无法正确读取目标文件内容,排序函数逻辑完全错误,无法完成排序操作。

相关代码与文件内容

读取文件的代码

void getStringsFromFile() {
    ifstream database;
    database.open("Database.txt", ios::app | ios::in | ios::binary);

    if (!database) {
        cout << "Kunne ikke indlaese filen..." << endl;
    }
    int count = 0, c = 0;
    string getString, tmp, str[256];
    for (int i = 0; i < 5; i++) {
        while (getline(database, getString)) {
            str[i] = getString;
            cout << "String: [" << count++ << "] " << str[i] << endl;
        }
    }
    sortStrings(getString);
}

写入文件的代码

if (database.is_open()) {
    database << list[i].navn << "\t" << list[i].addresse << "\t" << list[i].alder << "\t" << list[i].tlf << "\t" << "\n";
    database.close();
}

目标文件内容(第0行为空)

Kasper Jensen   
Jomfrugade 5    21  44556677

Victor Hansen   
Østergade 94    25  54644773

排序函数(无法正常工作)

void sortStrings(string &lines) {
    string* lines = nullptr;
    string temp;
    int count;

    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j >= 0; j--) {
            if (lines[j] > lines[j + 1]) {
                temp = lines[j];
                lines[j] = lines[j + 1];
                lines[j + 1] = temp;
            }
        }
    }
}

问题分析与修复方案

1. 读取函数的问题与修复

问题点:

  • 文件打开模式错误:ios::app会将文件指针定位到文件末尾,导致无法读取现有内容,应移除该模式。
  • 循环逻辑错误:外层for循环完全多余,内层while(getline)会一次性读完所有行,后续循环无法读取内容;同时str[i]会被不断覆盖,最终只保留最后一行数据。
  • 排序函数调用错误:传入的getString仅为最后一行的字符串,而非所有读取到的行集合。

修复后的读取函数:

#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>

using namespace std;

void getStringsFromFile();
void sortStrings(vector<string>& lines);
void writeToFile(const vector<string>& lines);

void getStringsFromFile() {
    ifstream database("Database.txt", ios::in | ios::binary);
    if (!database) {
        cout << "Kunne ikke indlaese filen..." << endl;
        return;
    }

    vector<string> str;
    string getString;
    int count = 0;
    while (getline(database, getString)) {
        // 跳过空行(可选,根据需求调整)
        if (!getString.empty()) {
            str.push_back(getString);
            cout << "String: [" << count++ << "] " << getString << endl;
        }
    }
    database.close();

    sortStrings(str);
    writeToFile(str);
}

2. 排序函数的问题与修复

问题点:

  • 变量重定义:参数string &lines与内部string* lines = nullptr重名,且指针为空,直接访问会导致崩溃。
  • count变量未初始化,循环条件i < count -1无意义。
  • 内层循环j >=0是死循环,排序逻辑完全错误。

修复后的插入排序函数:

void sortStrings(vector<string>& lines) {
    int n = lines.size();
    for (int i = 1; i < n; i++) {
        string key = lines[i];
        int j = i - 1;
        // 将比key大的元素向后移动
        while (j >= 0 && lines[j] > key) {
            lines[j + 1] = lines[j];
            j--;
        }
        lines[j + 1] = key;
    }
}

或者直接使用C++标准库的sort函数(更简单高效):

void sortStrings(vector<string>& lines) {
    sort(lines.begin(), lines.end());
}

3. 写入函数的问题与修复

问题点:

  • 每次写入后立即关闭文件,若循环写入多个数据,会导致后续写入失败。
  • 写入时末尾多了一个\t,可能导致文件出现多余空白。

修复后的写入函数:

void writeToFile(const vector<string>& lines) {
    ofstream outFile("SortedDatabase.txt");
    if (!outFile) {
        cout << "Kunne ikke oprette filen..." << endl;
        return;
    }

    for (const string& line : lines) {
        outFile << line << endl;
    }
    outFile.close();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:05:29