寒江皓月 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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)