2010-02-09 2 views
1

polindrom처럼 단어 ==> drow의 맵을 만들려고합니다 ... 문제는 "strtok"의 최종 레벨에 있습니다 ... 먼저 다음으로 나눕니다. strtok (NULL, "")을 수행 할 때 호출; 괜찮아. 내가 두 번째 문자열 "poly_buffer"를 추가 할 때 문제는 ... ... 그것이 작동 보인다 내가 잘못C++ strtok problem

#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); 
} 

를하고있는 중이 야 무엇인가?

+0

찾고있는 단어는 "회문"입니다. –

+0

'main'의 마지막 줄에있는 무한 루프는 무엇입니까? 또한, 누가 그 '새'에 의해 예약 된 메모리를 할당 해제거야? – Manuel

답변

4

strtok를 모두 호출

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

가 서로 방해를, 당신은 그들에게 하나 하나를 처리해야 - 당신이 그들을 할 수 없다 런타임 라이브러리에서 정적 메모리를 공유하기 때문에 동시에. 즉, 먼저

그 사람 페이지에서 strtok를

+0

덕분에 많이 할 것입니다. – kaycee

+0

@kayce - Anders가 맞습니다. strtok_r (GCC) 또는 strtok_s (VC++)와 같은 strtok의 재진입 버전을 사용해야합니다. 또는 Neil이 말한 것처럼 C++이 제공해야하는 우수한 대안을 사용하는 것이 더 좋습니다. – Manuel

2

C++을 사용하는 경우 왜 지구에서 strtok을 사용합니까? 단어 포함 tokenise하는 이제 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; 
    } 
} 
+0

더 좋은 방법이 있다는 것을 알고 있지만 그냥 cstring을 테스트하고 있습니다 – kaycee

1

에 대한 런타임 참조 문서를 참조 /// "strtok를을 (NULL, ("버퍼) "")이 끝날 때까지, 다음 strtok를 할 (poly_buffer를, "") strtok를 할 strtok, strtok_r :

"Avoid using these functions."