首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++排字程序

2013-12-10 
c++排版程序给一个txt(simple.txt),里面有一长串文字(英文),要求排版排成每行80字符(每个字母,空格算一

c++排版程序
给一个txt("simple.txt"),里面有一长串文字(英文),要求排版排成每行80字符(每个字母,空格算一字符),单词不能被换行隔断,一行不足80字符用空格平均地补上,然后把排版结果输出到新txt文件里,这个程序该怎么写?(简单的说效果和Word里自动排出来的一样)
[解决办法]
添加了单词不受换行影响的功能:


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

static const int LINE_MAX = 80;
static const char FILL_CHAR = ' ';
int main()
{
    ifstream fin("in.txt");
    ofstream fout("out.txt");
    string line;
    int index = 0;
    int line_no = 0;    // line number
    while (getline(fin, line))
    {
        line_no++;
        int pos = 0;
        int len = line.size();
        while (true)
        {
            int len_rest = len - pos;
            if (len_rest <= LINE_MAX)
            {
                string s(line, pos, len_rest);
                s.append(LINE_MAX - len_rest, FILL_CHAR);
                fout << s << endl;
                break;
            }
            else
            {
                int seg_len = LINE_MAX;
                while (seg_len > 0 && !isspace(line[pos + seg_len - 1]))
                {
                    seg_len--;
                }
                if (seg_len == 0)
                {
                    cout << "WARNING: A WORD WITH LENGTH EXCEEDS LINE_MAX: " << LINE_MAX << endl;
                    seg_len = LINE_MAX;
                }
                string s(line, pos, seg_len);
                s.append(LINE_MAX - seg_len, FILL_CHAR);
                fout << s << endl;
                pos += seg_len;
            }
        }
    }
    
    fin.close();
    fout.close();
    return 0;
}

热点排行