[土狗之路]coursera C語言進階習題 文字排版

編程題#3:文字排版

來源: POJ (Coursera聲明:在POJ上完成的習題將不會計入Coursera的最後成績。)

注意: 總時間限制: 1000ms 內存限制: 65536kB

描述

給一段英文短文,單詞之間以空格分隔(每個單詞包括其前後緊鄰的標點符號)。請將短文重新排版,要求如下:

每行不超過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 <cstring>
using namespace std;
int main()
{
	char words[1000][40]; //用於保存每一個單詞
	int wordsLen[1000]; // 記錄每一個單詞的長度
	int n; // 需要處理的單詞總數
	cin >> n;
	cin.get();//cin之後要用cin.get()讀取換行符,一開始沒注意到錯誤在這裏,還是基礎不牢靠
	for (int i = 0; i < n;i++) //輸入單詞數據,處理後得到每個單詞的長度
	{
		char temp;
		for (int j = 0; j < 40;j++) {
			cin.get(temp); 				
				if (temp != ' '&&temp != '\n') {
					words[i][j] = temp;
					
				}
				else
				{
					wordsLen[i] = j;
					break;
				}
			}
		
	}
	//先輸出第一個單詞
	int length = wordsLen[0];
	for (int j = 0; j < wordsLen[0]; j++)
		cout << words[0][j];
	for (int i = 1; i < n; i++)
	{
		//如果該單詞,連同前面的一個空格加入後不換行,則輸出空格和該單詞
		if (length + 1 + wordsLen[i] <= 80)
		{
			length = length + 1 + wordsLen[i];
			cout << ' ';
			for (int j = 0; j < wordsLen[i]; j++)
				cout << words[i][j];
		}
		else//如果該單詞,連同前面的一個空格加入後換行,則輸出回車和該單詞,另外重置本行現有長度爲單詞長度
		{
			cout << endl;
			length = wordsLen[i];
			for (int j = 0; j < wordsLen[i]; j++)
				cout << words[i][j];
		}
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章