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

C语言读入TXT文本进入链表检测空格有关问题

2012-08-10 
C语言读入TXT文本进入链表检测空格问题#include stdio.h#include stdlib.h#include string.h#define

C语言读入TXT文本进入链表检测空格问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 100

struct telebook{
  char nocor[N];
  char wacor[N];
  struct telebook *next;
}; /*--------- 定义链表 -------*/
struct telebook *next_list(struct telebook *last)
{
  /*-----这个函数用于新建一个链表单元,并返回这个新单元的指针--*/
  struct telebook *next;
  next=(struct telebook*)malloc(sizeof(struct telebook));/*-这句用于给next指针申请内存*/
  return next;
}

/*-------- 这个函数用来给链表添加数据 -*/
struct telebook *add(struct telebook *t,char *nocor,char *wacor)
{
  struct telebook *next;
  next=next_list(t);
  strcpy(next->nocor,nocor);
  strcpy(next->wacor,wacor);
  return next;
}

int main(int argc,char *argv[])
{
  struct telebook *head,*temp;/*----- head是链表的开头 temp是临时变量-*/
  FILE *fp;

  char buf1[N]; /*----- 缓冲区 -*/
  char buf2[N];
  int i=0;

  if(argc!=2){
  fprintf(stderr,"Usage %s filename\n",argv[0]);
  exit(0);
  }/*---------- 判断参数个数 ---------*/


  if((fp=fopen(argv[1],"r"))==NULL){
  printf("Can't open the file:%s",argv[1]);
  exit(0);
  }/*--------- 打开文件-------*/

  head=temp=(struct telebook*)malloc(sizeof(struct telebook));/*-这行给head申请内存单元*-/
  while(fgets(buf1,N,fp)!=NULL & fgets(buf2,N,fp)!=NULL){

  /*--- fgets读取一行数据遇到'\n'结束(就是回车啦)-*/
  if(buf1[strlen(buf1)-1]=='\n')
  buf1[strlen(buf1)-1]='\0';
  if(buf2[strlen(buf2)-1]=='\n');
  buf2[strlen(buf2)-1]='\0';

  temp=add(temp,buf1,buf2); /*-add函数返回下一个链表单元的指针-*/
  printf("nocor:%s\twacor:%s\n",temp->nocor,temp->wacor);
  /* ---这行打印读到的数据--*/
  }

  getchar();
  return 0;
}

经过调试,非常好用,但是文件格式只能写成
www.1.com
1.1.1.1
www.2.com
2.2.2.2

可是我的问题是同时需要检测空格和回车来区分数据
我的TXT里面内容是
www.1.com 1.1.1.1
www.2.com 2.2.2.2
像这样的,可是我把
  if(buf1[strlen(buf1)-1]=='\n')
  buf1[strlen(buf1)-1]='\0';
  if(buf2[strlen(buf2)-1]=='\n');
  buf2[strlen(buf2)-1]='\0';

if改成buf1[strlen(buf1)-1]==' '就无法检测了,更不用说 if(buf1[strlen(buf1)-1]=='\n'||buf1[strlen(buf1)-1]=' ')
十分茫然,希望赐教,我用0x20代替空格也不行。。


[解决办法]
函数原型:extern char *strtok(char *string, char *seps)

参数说明:string为源字符串,seps为指定的分隔符,是一个分隔字符串的集合。

所在库名:#include <string.h>
 
函数功能:将字符串string中所有在seps中出现的分隔符替换掉。
 
返回说明:返回指向下一个标记串。当没有标记串时则返回空字符NULL。

其它说明:

 当第一次调用strtok函数的时候,strtok函数跳过seps中的第一个分隔符,同时返回在string中的出现的第一个分隔符的位置的指针,用一个空字符'\0'终止。

通过循环,经过多次调用strtok函数,seps中更多的分隔字符都会被'\0'替换掉,最终输出我们意图实现的字符串。

实例:

/* MSDN提供 */
#include <string.h>
#include <stdio.h>

char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;

void main( void )
{
printf( "%s Tokens:", string );
token = strtok( string, seps ); /* Establish string and get the first token: */
while( token != NULL )
{
printf( " %s", token ); /* While there are tokens in "string" */
token = strtok( NULL, seps ); /* Get next token: */
}
}

热点排行