⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pex8_6.cpp

📁 数据结构C++代码,经典代码,受益多多,希望大家多多支持
💻 CPP
字号:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#pragma hdrstop

#include "array.h"
#include "strclass.h"

void main(void)
{
	// string pool
	Array<char> pool;
	// array of starting indices for lines
	Array<int> line;
	// current pool index and line index
	int poolIndex = 0, lineIndex = 0;
	// used to determine if pool must be resized
	int spaceRequired, spaceLeft;
	int i,N;
	String s;
	ifstream fin;

	cout << "Enter the file name: ";
	cin >> s;
	fin.open(s,ios::in | ios::nocreate);
	if(!fin)
	{
		cerr << "File " << s << " cannot be opened" << endl;
		exit(1);
	}

	// read lines until end of file
	while(s.ReadString(fin) != -1)
	{
		// space required for line. includes NULL character
		spaceRequired = s.Length()+1;
		// space left in pool is pool size - current pool index
		spaceLeft = pool.ListSize()-poolIndex;
		// if there is not enough space left in pool, we resize pool
		if (spaceRequired > spaceLeft)
			// new size is current size + additional space needed.
			// add 80 bytes and perhaps avoid another resize for awhile
			pool.Resize(pool.ListSize() + (spaceRequired - spaceLeft) + 80);
		// copy the line into the pool
		strcpy(&pool[poolIndex], s);
		
		// insert the pool index into line
		line[lineIndex] = poolIndex;
		// increment the pool index
		poolIndex += spaceRequired;
		// increment theh line index
		lineIndex++;
		// if new index has passed end of line, add 10 more elements
		if (lineIndex >= line.ListSize())
			line.Resize(line.ListSize() + 10);
	}

	cout << "Enter N: ";
	cin >> N;
	
	// if number of lines (lineIndex) is less than N,
	// list all the lines of the file
	if (lineIndex < N)
		for(i=0;i < lineIndex;i++)
			cout << &pool[line[i]] << endl;
	else
		// list last N lines
		for(i=lineIndex-N;i < lineIndex;i++)
			cout << &pool[line[i]] << endl;
}

/*
<Run>

<file "pex8_6.dat">

This line 1.
This is line 2.
This is line 3.
The end of this text file is approaching (line 4)
There are two more lines to go (line 5).
Line 6.
Last line (line 7).

<Run #1>
Enter the file name: pex8_6.dat
Enter N: 3
There are two more lines to go (line 5).
Line 6.
Last line (line 7).

<Run #2>

Enter the file name: pex8_6.dat
Enter N: 20
This line 1.
This is line 2.
This is line 3.
The end of this text file is approaching (line 4)
There are two more lines to go (line 5).
Line 6.
Last line (line 7).
*/
	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -