c ++ strtok问题

时间:2010-02-09 14:32:33

标签: c++ string strtok

我正在尝试创建一个word ==> drow的地图,就像polindrom ... 问题是在“strtok”的最后一级...... 首先我拆分它,然后在执行strtok时后续调用(NULL,“”);它工作正常。 问题是当我添加第二个字符串“poly_buffer”...似乎它适用于它....

#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <string>
using namespace std;

void poly(char *buffer)
{
 char temp;
 for (int i=0; i<=strlen(buffer); i++)
 {
  int word_start = i, word_stop = i;

  while (buffer[i] != 32 && buffer[i] != '\0') { i++; word_stop++; }
  word_stop--;

  //swap chars until the middle of word
  while (word_stop >= word_start)
  {
   //swap the chars
   temp = buffer[word_stop];
   buffer[word_stop] = buffer[word_start];
   buffer[word_start] = temp;
   word_stop--;
   word_start++;
  }
  word_start = i;

 }
}


void main()
{
 FILE *fp;
 char *buffer;
 char *poly_buffer;
 long file_size;
 map<string,string> map_poly;

 fp = fopen("input.txt", "r");

 if (fp == NULL) { fputs("File Error",stderr); exit(1); }

 //get file size
 fseek(fp,1,SEEK_END);
 file_size = ftell(fp);
 rewind(fp);

 //allocate memory
 buffer = new char[file_size+1];
 poly_buffer = new char[file_size+1];

 //get file content into buffer
 fread(buffer,1, file_size,fp);
 strcpy(poly_buffer,buffer);

 buffer[file_size] = '\0';
 poly_buffer[file_size] = '\0';

 poly(buffer);

 buffer = strtok(buffer," ");
 poly_buffer = strtok(poly_buffer," ");

 while (buffer != NULL)
 {
  map_poly[buffer] = poly_buffer;
  printf("%s ==> %s\n", buffer, poly_buffer);
  buffer = strtok(NULL," ");
  poly_buffer = strtok(NULL," ");
 }

 fclose(fp);
 while(1);
}

我做错了什么?

3 个答案:

答案 0 :(得分:4)

两个strtok调用

buffer = strtok(buffer, " ");
poly_buffer = strtok(poly_buffer," ");

彼此干扰,你需要逐个处理它们 - 你不能同时处理它们,因为它们在运行时库中共享静态内存。即首先执行strtok(缓冲区,“”)strtok(NULL,“”)直到结束,然后执行strtok(poly_buffer,“”)///

请参阅strtok的运行时参考文档

答案 1 :(得分:2)

如果您使用的是C ++,为什么在地球上会使用strtok?使用stringstream标记和向量包含单词:

#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  istringsream is( "here are some words" );
  string word;
  vector <string> words;
  while( is >> word ) {
    words.push_back( word );
  }
  for ( unsigned int i = 0; i < words.size(); i++ ) {
    cout << "word #" << i << " is " << words[i] << endl;
  }
}

答案 2 :(得分:1)

来自strtok的手册页,strtok_r:

"Avoid using these functions."