题解 CF5B 【Center Alignment】

· · 题解

这题不是很难,大体思路就是while(getline(cin,str))这样读入(若干行要用while,因为有空格要用getline),边读入边更新最大值。

然后挨个处理每个字符串要加多少空格,这是这道题的重头戏:

题目已经分析完了,上代码!

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string str[10010];
int main()
{
    int tot=0,cnt=0,maxn=0,k;
    /*tot是多少行要处理的字符串
    cnt是出现无法刚好对齐的次数
    maxn是长度最大字符串的长度
    k临时存储每个字符串的长度。*/
    while(getline(cin,str[++tot]))//循环读入
        k=str[tot].size(),maxn=max(k,maxn);//更新最长
    string ud(maxn+2,'*');tot-=1;//ud是边框
    //这里我们会多读入一个东东,所以tot要-1
    cout<<ud<<endl;//输出边框
    for(int p=1;p<=tot;p++)
        if(str[p].size()==0)//特判为空行的情况
        {
            string s(maxn,' ');
            cout<<"*"<<s<<"*"<<endl;
        }
        else
            if((maxn-str[p].size())%2==0) //可以完美对齐
            {
                string s((maxn-str[p].size())/2,' ');
                cout<<"*"<<s<<str[p]<<s<<"*"<<endl;
            }
            else//不能完美对齐
            {
                string s((maxn-str[p].size())/2,' ');
                cnt++;//出现不能完美对齐的次数+1
                if(cnt%2)//如果不是2的倍数靠左
                    cout<<"*"<<s<<str[p]<<s<<" *"<<endl;
                else//否则靠右
                    cout<<"* "<<s<<str[p]<<s<<"*"<<endl;
            }
    cout<<ud<<endl;
}