pex8_9.cpp
来自「数据结构C++代码,经典代码,受益多多,希望大家多多支持」· C++ 代码 · 共 118 行
CPP
118 行
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#pragma hdrstop
#include "strclass.h"
void main(void)
{
// "line" is dynamic array containing the lines of file "fname".
// poundstr, ampstring are replacement strings
String *line, poundstr, ampstring;
char fname[30];
// input file
ifstream fin;
int n, start, pos, nlines, i;
// prompt for file name and open the file
cout << "Enter the file name: ";
cin >> fname;
fin.open(fname,ios::in | ios::nocreate);
if (!fin)
{
cerr << "Cannot open the file " << fname << endl;
exit(1);
}
// request an upper bound on the number of lines in the file
cout << "Enter the maximum number of lines in "
<< fname << ": ";
cin >> n;
// read the newline following n
char c;
cin.get(c);
// allocate an array of n String objects
line = new String [n];
if (line == NULL)
{
cerr << "Memory allocation failure!" << endl;
exit(1);
}
// read the lines of the file, placing each line
// into one of the strings in line
i = 0;
while(line[i].ReadString(fin,'\r') != -1 && i < n)
i++;
// number of lines in the file
nlines = i;
// read the replacement strings
cout << "Enter poundstr: ";
poundstr.ReadString();
cout << "Enter ampstring: ";
ampstring.ReadString();
cout << endl;
// perform the replacements for each line
for(i=0;i < nlines;i++)
{
// starting position for searching line[i]
start = 0;
// find all occurrences of '#' in line[i] and
// replace each by poundstr
while((pos = line[i].Find('#',start)) != -1)
{
// remove '#' at position pos
line[i].Remove(pos,1);
// insert poundstr at position pos
line[i].Insert(poundstr,pos);
// move forward and search for the next '#'
start = pos+1;
}
// use the same strategy to perform replacement for '&'
start = 0;
while((pos = line[i].Find('&',start)) != -1)
{
line[i].Remove(pos,1);
line[i].Insert(ampstring,pos);
start = pos+1;
}
cout << line[i] << endl;
}
}
/*
<Run>
<file "pex8_9.dat">
Dear #
Your lucky gift is available at &. By going to & and
identifying your name, the attendant will give you your
prize. Thank you # for your interest in our contest.
Sincerely,
The String Man
Enter the file name: pex8_9.dat
Enter the maximum number of lines in pex8_9.dat: 20
Enter poundstr: John Henry
Enter ampstring: Metro Mart
Dear John Henry
Your lucky gift is available at Metro Mart. By going to Metro Mart and
identifying your name, the attendant will give you your
prize. Thank you John Henry for your interest in our contest.
Sincerely,
The String Man
*/
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?