我的程序(5):字符界面排版

///
//
// FileName :  edit.cpp
// Creator  :  温铭
// Date     :  2007-3-12
// Comment  :  从文件test.txt中读入4K以内的纯英文文本,在字符界面下排版。
//             要求每行两边有5个空格,调整单词之间的间隔使文本显示美观。
//
///

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

bool openfile( ifstream &infile );       //打开文件
void edit( ifstream &infile );           //对文本进行排版
void display( vector<string> &text );     //输出排版后的文本
void closefile( ifstream &infile );      //关闭文件

//全局变量
const LENGTH = 80;              //一行的总长度
const BLACK = 5;                //每边空格的长度
const WIDTH = 80 - 2*BLACK;     //除去两边空格后,一行可以存放字符的长度

int main()

 ifstream infile( "test.txt" );    // 打开文件test.txt用于输入
 if ( !openfile(infile) )
  return -1;
 edit(infile);  
    closefile(infile);
    return 0;
}


bool openfile( ifstream &infile )
{
 if ( !infile )                    //如果文件不能打开,返回错误信息
 {
 cerr << "unable to open input file: "
   << "test.txt" << " -- bailing out!/n";
 return false;
 }
 return true;
}


void closefile( ifstream &infile )
{
 infile.close();
}

void edit( ifstream &infile )
{
    string buffer;
    vector<string> text;

 while ( infile >> buffer )
  text.push_back( buffer );    //把各个单词保存在向量里面
 
 display(text);
}

void display( vector<string> &text )
{
 string blank(BLACK,'*');        //边界
 string::size_type count = 0;    //字符数    
    int num = 0;                   //单词数

 vector<string>::const_iterator iter = text.begin();
 vector<string>::const_iterator temp = iter;

 while( iter != text.end() )       
 {
  if ( iter == text.end() - 1 )     //如果到达最后一个单词,就打印出来并跳出循环
  {
   cout << blank;                       //打印空白符
   num++;
   while ( num-- )
   {
    cout << *temp++<<string(1,'*');
   }
   break;                      //跳出循环
  }

  if ( count + iter->size() >= WIDTH )
   //如果加上下一个单词数就超过一行的最大限制,就打印出来
  {
   int interval = WIDTH - count ;       //间隔数
 
   cout << blank;                       //打印空白符
        
   while ( --num && interval-- )       //前interval个单词后面都跟2个空格
   {
    cout << *temp<<string(2,' ');
    temp++;
   }
   while ( num-- )
   {
    cout << *temp<<string(1,' ');  //间隔分配完以后,单词后面跟一个空格
    temp++;
   }
   if ( interval > 0 )                //如果还有间隔,都分配给最后一个单词前面
    cout << string(interval,'*')<< *temp++ <<blank<<endl;
   else
    cout << *temp++<< blank <<endl;
   num = 0;
   count = 0;                        //清零计数器
   iter = temp;
  }
  else
  {
   num++;                              //单词增加一个
   count = count + iter->size() + 1;   //单词及后面所跟空格所占的空间
   iter++;
  }
 }
}
 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值