寒江皓月 2015-07-29 14:24 采纳率: 100%
浏览 3086
已采纳

C++编程实现文字排版 Debug排错

描述
给一段英文短文,单词之间以空格分隔(每个单词包括其前后紧邻的标点符号)。请将短文重新排版,要求如下:

每行不超过80个字符;每个单词居于同一行上;在同一行的单词之间以一个空格分隔;行首和行尾都没有空格。

输入
第一行是一个整数n,表示英文短文中单词的数目. 其后是n个以空格分隔的英文单词(单词包括其前后紧邻的标点符号,且每个单词长度都不大于40个字母)。
输出
排版后的多行文本,每行文本字符数最多80个字符,单词之间以一个空格分隔,每行文本首尾都没有空格。
样例输入:
84
One sweltering day, I was scooping ice cream into cones and told my four children they could "buy" a cone from me for a hug. Almost immediately, the kids lined up to make their purchases. The three youngest each gave me a quick hug, grabbed their cones and raced back outside. But when my teenage son at the end of the line finally got his turn to "buy" his ice cream, he gave me two hugs. "Keep the changes," he said with a smile.
样例输出:
One sweltering day, I was scooping ice cream into cones and told my four
children they could "buy" a cone from me for a hug. Almost immediately, the kids
lined up to make their purchases. The three youngest each gave me a quick hug,
grabbed their cones and raced back outside. But when my teenage son at the end
of the line finally got his turn to "buy" his ice cream, he gave me two hugs.
"Keep the changes," he said with a smile.
我的解决方案:

 #include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char words[100][40];//用于保存每一个单词
    int wordsLen[100];// 记录每一个单词的长度
    int n;//  需要处理的单词总数
    cin>>n;
    //输入单词数据,处理后得到每个单词的长度
    for(int i=0;i<n;i++)
    {
        cin>>words[i];
        wordsLen[i]=strlen(words[i]);
    }

    //先输出第一个单词
    int length=wordsLen[0];
    cout<<words[0];
    for(int i=1;i<n;i++)
    {
            //如果该单词,连同前面的一个空格加入后不换行,则输出空格和该单词   
            if(length+1+wordsLen[i]<=80)
            {
                length=length+1+wordsLen[i];
                cout<<" "<<words[i];
            }
            else
            {
                //该单词不能在本行输出了,如果length=80自动换行,否则要手动换行。
                if(length<80)
                {
                    cout<<endl;
                }
                //输出下一行第一个单词,重新对下一行的输出字符长度进行统计。
                length=wordsLen[i];
                cout<<words[i];
            }
    }
    cout<<endl;
    return 0;
}

提交后错误,谁能帮我分析分析,程序逻辑上哪里有问题?

原题目

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip