1

我正在尝试创建 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);
}

我究竟做错了什么 ?

4

3 回答 3

4

两个 strtok 调用

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

相互干扰,你需要一个一个地处理它们——你不能同时处理它们,因为它们在运行时库中共享静态内存。即先做 strtok(buffer," ") strtok(NULL, " ") 直到结束,然后做 strtok( poly_buffer, " ")///

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

于 2010-02-09T14:37:09.280 回答
2

从 strtok 的手册页中,strtok_r:

"Avoid using these functions."
于 2010-02-09T18:06:01.533 回答
2

如果你使用 C++,你到底为什么要使用 strtok?使用字符串流进行标记,使用向量来包含单词:

#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;
  }
}
于 2010-02-09T14:36:44.257 回答