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

C++实现单词逐字反转保留非字母字符及输出问题求解

问题修复方案

原有代码核心问题

  • 读写逻辑顺序错误:读取文件时直接将原始未处理内容写入了输出文件,反转函数调用在读取循环外部,仅能拿到最后一行输入,且处理结果没有写入输出流
  • 边界判断写死:硬编码循环14次处理单词,无法适配不同长度的文本,处理到行尾最后一个无空格收尾的单词时会触发越界
  • 字符保留逻辑缺失:仅按空格切割单词反转,无法保留多个连续空格、标点等非字母字符的原有位置,也没有做处理结果的完整拼接
  • 调试逻辑冗余:反转函数内大量打印调试信息,没有返回处理后的完整字符串,无法对接输出流程

修正后完整代码

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std; 

string processLine(string line); 

int main(){
    ifstream inData; 
    ofstream outData; 
    string line; 

    inData.open("input.txt"); 
    outData.open("output.txt"); 

    while(getline(inData, line)){
        outData << processLine(line) << '\n';
    }

    inData.close(); 
    outData.close(); 
    return 0; 
}

string processLine(string line){
    int len = line.length();
    int wordStart = 0;
    while (wordStart < len) {
        // 跳过非字母字符
        if (!isalpha(line[wordStart])) {
            wordStart++;
            continue;
        }
        // 定位当前连续字母段的结束位置
        int wordEnd = wordStart;
        while (wordEnd < len && isalpha(line[wordEnd])) {
            wordEnd++;
        }
        // 反转当前字母段
        reverse(line.begin() + wordStart, line.begin() + wordEnd);
        wordStart = wordEnd;
    }
    return line;
}

实现说明

  • 采用双指针遍历逻辑,不需要提前切割单词、事后拼接:左指针标记单词起始位置,右指针扫到非字母字符就停止,反转两个指针之间的字母段即可
  • 所有非字母内容(空格、标点、特殊符号)都不会被修改,位置完全保留,不存在空格丢失、标点错位的问题
  • 没有硬编码长度限制,自动适配任意长度的单句、多句输入,行尾无空格的场景也能正常处理
  • 逐行读取、逐行处理、逐行写入,不会出现内容遗漏,输入The cat sat on the mat!时可正确输出ehT tac tas no eht tam!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:30:55