文字排版(C程序设计进阶第5周)

时间:2021-05-01 06:37:27

问题描述
给一段英文短文,单词之间以空格分隔(每个单词包括其前后紧邻的标点符号)。请将短文重新排版,要求如下:
每行不超过80个字符;每个单词居于同一行上;在同一行的单词之间以一个空格分隔;行首和行尾都没有空格。
输入
第一行是一个整数n,表示英文短文中单词的数目. 其后是n个以空格分隔的英文单词(单词包括其前后紧邻的标点符号,且每个单词长度都不大于40个字母)。
输出
排版后的多行文本,每行文本字符数最多80个字符,单词之间以一个空格分隔,每行文本首尾都没有空格。
样例输入

84
One sweltering day, I was scooping ice cream into cones and told my four children they could "buy" acone 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 fourchildren they could "buy" a cone from me for a hug. Almost immediately, the kidslined 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 endof the line finally got his turn to "buy" his ice cream, he gave me two hugs."Keep the changes," he said with a smile.

源码
源码一:

//注意在windows下编程控制台默认为80字符宽度,到了80个字符会自动换行,其他环境下不一定如此,所以不用作特殊处理
#include <iostream>
#include<string.h>
using namespace std;

int main()
{
int words = 0, sum = 0;
cin >> words;
char str[41]={0};
for (int i = 0; i < words; i++)
{
cin >> str;
if (sum + 1 + strlen(str) > 80)
{
cout << endl;
sum = 0;
}
else if(i>0)
{
cout << " ";
sum++;
}
cout << str;
sum += strlen(str);
}
return 0;
}

源码二:

#include<stdio.h>
#include<string.h>
#define MAX 40
#define LINE 80

int main()
{
int i, n, len;
int end = 0;
char word[MAX+1];
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%s", word);
len = strlen(word);
if (end + len +1 > LINE)
{
printf("\n");
end = 0;
}
else if(i>0)
{
printf(" ");
end++;
}
printf("%s", word);
end += len;
}
return 0;
}