[英]c++ strtok problem
我正在尝试创建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);
}
我究竟做错了什么 ?
两个strtok调用
buffer = strtok(buffer, " ");
poly_buffer = strtok(poly_buffer," ");
彼此干扰,您需要一个一个地处理它们-您不能同时执行它们,因为它们共享运行库中的静态内存。 即首先执行strtok(buffer,“”)strtok(NULL,“”)直到结束,然后执行strtok(poly_buffer,“”)///
有关strtok的信息,请参见运行时参考文档
如果您使用的是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;
}
}
在strtok的手册页中,strtok_r:
"Avoid using these functions."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.