📄 cpp1.cpp
字号:
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
#include<stdio.h>
#include<string.h>
//定义各种变量
long over; //文件的结束位置
const int maxwordlength=20; //最大字的长度
const int maxlinewidth=80; //最大行宽
int position; //记录一行中的最后一个字的位置
int linewidth; //行宽
char line[maxlinewidth+1];//行数组
struct word
{char spelling[maxwordlength+1];//字数组
int length;
}word;
ifstream ist; //打开文件
//函数
//****************************************************************************************************
void readword()
{//读一个字
char n;
n =ist.get(); //从文本读入一个字
word.length=0;
while(n!=' ')
if(word.length<maxwordlength)
{word.length++;
word.spelling[word.length]=n;
n=ist.get();
if(ist.tellg()==over)
{word.length++;
word.spelling[word.length]=n;
break;}
}
}
void printline()
{//打印当前行
for(int pos=1;pos<=position;pos++)cout<<line[pos];
cout<<endl;
}
void startline()
{position=0;
}
void startparagraph()
{
printline();
startline();
}
void appendblank()
{//添加空格
word.length++;
word.spelling[word.length]=' ';
}
bool roomfor(int nmrofchars)
{//该字不能加入到当前行
return (position+nmrofchars)<=linewidth;
}
void appendword()
{for(int pos=1;pos<=word.length;pos++)
{position++;
line[position]=word.spelling[pos];
}
}
void adjusting() //调整并输出
{int rightmost; //表示右界
int leftmost; //表示左界
int extrablank; //剩余的空缺位置的数目
int nmrofgaps; //单词间的空隙数
int widening; //插入的空格数
leftmost=1;
while(line[leftmost]==' ') //求左边界
leftmost++;
rightmost=position;
while(line[rightmost]==' ') //求右边界
rightmost--;
nmrofgaps=0; //求单词间的间隙
for(int pos=leftmost;pos<=rightmost;pos++)
if(line[pos]==' ')nmrofgaps++;
extrablank=linewidth-position; //剩余的空缺位置
for(pos=1;pos<=rightmost;pos++)
if((pos>leftmost)&&(line[pos]==' '))
{widening=extrablank/nmrofgaps;
cout<<setw(widening+1)<<" ";
extrablank=extrablank-widening;
nmrofgaps--;
}
else cout<<line[pos];
cout<<endl;
}
void main()
{char ch;
do
{
cout<<"请输入行的宽度:";
cin>>linewidth;
if(linewidth>maxlinewidth)linewidth=maxlinewidth;
ist.open("Bill.txt",ios::binary|ios::in);
ist.seekg(0,ios::end);
over=ist.tellg();
ist.seekg(0,ios::beg);
readword();
int i=1;
while(i!=0){
if(ist.tellg()==over){i=0;}
if(word.spelling[1]=='P'&&word.spelling[2]=='A'&&word.spelling[3]=='R') startparagraph();
else{appendblank();
if(!roomfor(word.length))
{adjusting(); //调整并输出
startline(); //开始一个新的行
}
appendword(); //把该字加入到当前行
}//else
if(i==0)printline(); //打印最后一个字
else readword();
}
ist.close(); //关闭文件
cout<<endl;
cout<<"您想换一种格式输出吗?(Y/N)"<<endl;
cin>>ch;
}
while(ch=='Y');
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -