程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 解決方案-C++編程實現文字排版 Debug排錯

解決方案-C++編程實現文字排版 Debug排錯

編輯:編程綜合問答
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;
}

提交後錯誤,誰能幫我分析分析,程序邏輯上哪裡有問題?

原題目

最佳回答:


http://zhidao.baidu.com/link?url=njHxbL-kH-phHKN7o3wZrxeoLzpzuax71FftaanRAafvTtvZIWDDXNWYgqWeLERhoj9NkEaqQS-rrw7hnhyWrK

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved