求一个C++的小程序

来源:百度知道 编辑:UC知道 时间:2024/06/11 06:12:25
我现在读入一个文本,里面有一些词语用[]括起来了,并且[]后面是nt,我想把方括号和方括号里面的内容还有nt提取出来,并且输出到另外一个文本上,这个程序该怎么写??希望高手帮个忙,解决之后另外加分,谢谢!!

下面的程序代码希望对楼主有所帮助:

/*
* 读入一个文本,里面有一些词语用[]括起来了,并且[]后面是nt,
* 把方括号和方括号里面的内容还有nt提取出来,并且输出到另外一个文本上。
*/
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

void main()
{
ifstream in("input.txt");
ofstream out("output.txt");

if (in && out)
{
char *p1;
char *p2;
char *p3;
char buf[BUFSIZ];
char tmp[BUFSIZ];
while(in.getline(buf, BUFSIZ)) // 读取文件每一行
{
p1 = buf;
while((p2 = strchr(p1, '[')) != (char *)NULL) // 找到每一个字符“[”
{
p3 = p2 + 1;
while((p3 = strchr(p3, ']')) != (char *)NULL) // 找到后续每一个字符“]”
{
if (strncmp(p3+1, "nt", 2) == 0) // 如果字符“]”后面的两个字符为“nt”,则输出
{
strncpy(tmp, p2+1, p3-p2-1);
tmp[p3-p2-1] = 'n';
tmp[p3-p2+0] = 't';