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

C++文件IO中如何添加换行且不破坏token输出结构?

C++摩尔斯码转英文文件IO的换行问题解决

我用C++实现文件IO功能,将摩尔斯码翻译为英文,通过morseToEnglish()函数处理token并写入输出文件。目前输出内容正确但缺少换行,直接给每个token加endl或"\n"会导致每个token单独换行,期望实现输入每行对应输出一行,同时不破坏token的输出结构。

当前代码:

char morsing[256]; //reading line by line
if (inputfile.is_open())
{ 
    while (inputfile.getline(morsing, 256)) // reading line by line
    {                                    
        token = strtok(morsing, "|"); //break each line into tokens
        cout << "Read the input file: " << "morsingMC.mc" << endl;
        while (token != NULL)
        {
            outputfile << morseToEnglish(morsing); // 注意:此处参数应为token而非morsing
            token = strtok(NULL, "|");
        } 
    } 
}

实际输出:

123 456 789123 456 789123 456 789123 456 789123 456 789

预期输出:

123 456 789
123 456 789
123 456 789
123 456 789
123 456 789

注:morseToEnglish()是头文件中的摩尔斯码转英文函数,inputfile/outputfile分别为ifstream/ofstream类型。


解决方案

问题核心是处理完每行所有token后未添加换行,同时代码中存在参数传递错误(调用morseToEnglish时传了整个数组而非分割后的token)。修正后的代码如下:

char morsing[256];
if (inputfile.is_open())
{ 
    while (inputfile.getline(morsing, 256))
    {                                    
        char* token = strtok(morsing, "|");
        cout << "Read the input file: morsingMC.mc" << endl;
        
        while (token != NULL)
        {
            // 传递分割后的token给转换函数
            outputfile << morseToEnglish(token);
            token = strtok(NULL, "|");
            // 如果token转换后需要空格分隔,可添加此行:outputfile << " ";
        }
        // 每行处理完成后添加换行,对应输入的一行
        outputfile << endl;
    } 
}

说明

  1. 参数修正:将morseToEnglish(morsing)改为morseToEnglish(token),确保转换的是分割后的单个摩尔斯码token(原代码应为笔误,否则输出内容正确不符合逻辑)。
  2. 换行添加:在处理完当前行的所有token后(即内部while循环结束后)添加outputfile << endl;,这样每处理完一行输入,输出就换行一次,完美对应输入的行结构。
  3. 可选空格:如果token转换后需要用空格分隔,可在每次输出转换结果后添加outputfile << " ";,避免内容连在一起。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:17:08