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

如何避免C++中文本垂直输出?文件复制与数字修改场景下的格式修复方案

Fixing Vertical Line-by-Character Output in File Copy with Digit Modification

Hey there, the issue is super straightforward once you spot it! Let's break it down:

Your current code writes every single character followed by a newline ("\n") here:

out_file << ch << "\n";

That's why every character ends up on its own line vertically—you're forcing a line break after each one instead of keeping them grouped as lines like the original file.

The Fix (No Big Changes Needed!)

You don't have to touch any of your digit-modification logic or core file handling code. Just adjust where you add the newline:

  1. First, remove the "\n" from inside the character loop, so you just write each modified character to the output file without breaking the line:
    out_file << ch;
    
  2. Then, after you finish processing all characters in a single line (once the for loop ends), add a single newline to preserve the original line structure:
    out_file << "\n";
    

Modified Full Code

Here's what your code looks like with these tweaks (changes marked with comments, plus a tiny bug fix):

#include <iostream>
#include <fstream>
#include <ctype.h>
using namespace std;
int main() {
    string line;
    ifstream ini_file {"f.txt"};
    ofstream out_file {"f1.txt"};
    if(ini_file && out_file){
        while(getline(ini_file,line)){
            for (char ch : line) {
                if (isdigit(ch)){
                    if(ch!=57){ch++;}
                    // Fixed: changed assignment `=` to comparison `==` here
                    else if (ch==57){ch=48;}
                }
                // Removed newline from inside the character loop
                out_file << ch;
            }
            // Add newline after processing the entire line
            out_file << "\n";
        }
        cout << "Copy Finished \n";
    } else {
        printf("Cannot read File");
    }
    ini_file.close();
    out_file.close();
    return 0;
}

Quick side note: I fixed a tiny bug in your digit check—you used ch=57 (assignment operator) instead of ch==57 (comparison operator). The original code would have incorrectly set every digit to 57 before resetting it to 48, which wasn't your intended behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:22:34