2014-10-21 5 views
0

여러 줄의 문자열에서 후행 \ n을 제거한 다음 토큰에 추가하여 테이블을 나열하는 데 문제가 있습니다. 문자열은 입력 리디렉션 (< input.txt)을 사용하여 텍스트 파일에서옵니다.문자열에서 후행 줄 바꿈을 제거하는 중 문제가 발생했습니다.

텍스트 파일은 다음과 같습니다 : 이것은 내가 지금까지 무엇을 가지고

Little Boy Blue, Come blow your horn, The sheep's in the meadow, The 
cow's in the corn; Where is that boy Who looks after the sheep? Under 
the haystack Fast asleep. Will you wake him? Oh no, not I, For if I do 
He will surely cry. 

코드 : 당신은 큰 메모리 할당 문제가

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main() 
{ 
    int c; 
    char *line; 
    char *ptr; 
    char *pch; 
    line = (char *) malloc(1); 
    ptr = line; 
    for (;(*line = c = tolower(getchar())) != EOF; line++); 

    *line='\0'; 

    pch = strtok(ptr," \n,.-"); 
    while (pch != NULL) 
    { 
     printf ("%s\n", pch); 
     pch = strtok(NULL, " ?;,.-"); 
    } 
    return 0;  
} 
+1

코드가 char * 행에 1 바이트 만 할당하고 많은 코드가 (* 문자가 텍스트 파일에 있습니다. 이게 당신 문제 야? –

답변

3

; 1 바이트의 메모리를 할당 한 다음 많은 수의 문자를 읽어 들이고 끝에 null 바이트를 추가합니다. 문제를 해결해야합니다.

두 코드 사이의 구분 기호가 strtok()으로 바뀌어 코드가 약간 혼란 스럽습니다. 그건 가능하지만 두 번째와 물음표에 세미콜론을 넣지 않은 이유는 분명하지 않습니다 (느낌표와 콜론은 어떨까요?).

<ctype.h>에 선언되어 있습니다.

끝에있는 개행을 제거하는 가장 간단한 방법은 null 바이트로 겹쳐 쓰는 것입니다. 다른 줄 바꿈도 매핑해야하는 경우 데이터를 읽을 때 번역을 수행하십시오.

#include <ctype.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(void) 
{ 
    int c; 
    char *line = (char *)malloc(1); 
    size_t l_max = 1; 
    char *ptr = line; 

    if (line == 0) 
     return 1; // Report out of memory? 

    while ((c = tolower(getchar())) != EOF) 
    { 
     if (ptr == line + l_max - 1) 
     { 
      char *extra = realloc(line, 2 * l_max); 
      if (extra == 0) 
       return 1; // Report out of memory? 
      l_max *= 2; 
      line = extra; 
     } 
     *ptr++ = c; 
    } 

    if (*(ptr - 1) == '\n') 
     ptr--; 
    *ptr = '\0'; 

    static const char markers[] = " \n\t,.;:?!-"; 
    char *pch = strtok(line, markers); 

    while (pch != NULL) 
    { 
     printf ("%s\n", pch); 
     pch = strtok(NULL, markers); 
    } 
    return 0;  
} 

데이터에 개행을 남길 수도 있습니다. strtok()은 결국 건너 뜁니다.

관련 문제