如何使用C++提取出一个文件中的特定字符串里面的数字 数据例子如下

ARC a0_0 FROM t0_0 TO t0_1 TYPE 21
ARC a0_1 FROM t0_1 TO t0_2 TYPE 42
ARC a0_2 FROM t0_0 TO t0_3 TYPE 31
ARC a0_3 FROM t0_2 TO t0_4 TYPE 45
ARC a0_4 FROM t0_3 TO t0_5 TYPE 49
ARC a0_5 FROM t0_3 TO t0_6 TYPE 45
ARC a0_6 FROM t0_1 TO t0_7 TYPE 4

我要提取出 “FROM 后的t0_0 中 _后面的0” 和 “TO 后的t0_1 中 _后面的1”

从而转换成
0 1
1 2
0 3
2 4
3 5
3 6
1 7
这样一个文件输出。

#include<iostream>
#include<fstream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
 ifstream in("e:\\test.txt");
 if(!in)
  exit(-1);
 char str[50];
 string sstr;
 while(!in.eof())
 {
  memset(str,0,sizeof(str));
  in.getline(str,50,'\n');
  char *pstart=strstr(str,"FROM t0_");
  if(pstart)//表示能找到那个子句
   pstart=pstart+strlen("FROM t0_");
  char *pend=strstr(pstart,"  TO");
  if(pend)
   *pend='\0';
  int fromnum=atoi(pstart);
  pstart=pend+1;
  pstart=strstr(pstart,"TO  t0_");
  if(pstart)
   pstart=pstart+strlen("TO  t0_");
  pend=strstr(pstart," TYPE");
  if(pend)
   pend='\0';
  int tonum=atoi(pstart);
  printf("%d %d\n",fromnum,tonum);
 }
 in.close();
 system("pause");
 return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-17

#include <stdio.h>
main()
{
char a,b;
FILE *fp=fopen("data.txt","r");
while (!feof(fp))
{
fscanf(fp,"%*[^_]_%*s %*[^_]_%c TO %*[^_]_%c\n",&a,&b);
printf( "%c %c\n",a,b);
}
fclose(fp);
}

追问

整体数据基本是这样的,你的代码可能需要稍微修改一下。

能帮我修改一下吗?最后再帮我加一下总共有几对,然后输出txt好吗?

十分感谢

追答

你还是贴文字版的 或者 传个txt上来

这图片里的内容 不至于让我全部手敲吧?

追问

@TASK_GRAPH 0 {
PERIOD 400
TASK t0_0 TYPE 8
ARC a0_0 FROM t0_0 TO t0_1 TYPE 21
HARD_DEADLINE d0_0 ON t0_4 AT 400
}
你把中间的复制多遍就行

追答

#include <stdio.h>
main()
{
int n=0;
char a,b;
FILE *fp = fopen("data.txt","r");
FILE *fw = fopen("result.txt","w");
while (!feof(fp))
{
if (fscanf(fp,"%*[^_]_%*s %*[^_]_%c TO %*[^_]_%c\n",&a,&b)==2)
{
printf("%c %c\n",a,b);
fprintf(fw, "%c %c\n",a,b);
n++;
}
}
fclose(fp);
fclose(fw);
printf("result save to file result.txt OK.\n");
printf("total is %d pair(s).\n",n);
}

本回答被提问者采纳
第2个回答  2013-06-17
用正则表达式最方便,不建议用C++,
用任何支持正则表达式的脚本语言如Python,Perl之类的

一定用C++的话你用<regex>的正则表达式,或者简单使用字符串比较来处理
相似回答