2016-11-23 1 views
1

파일 입력 및 포인터로 작업 한 것은 이번이 처음입니다. 코드가 엉망인 것 같아서 죄송합니다. 나는 다른 Stack Overflow 솔루션을 참고로보고 있었다. 내 코드는 입력 텍스트의 단어가 1000자를 초과하지 않는다고 가정 할 수있는 파일에서 가장 긴 단어를 찾습니다.C : 파일 입력 순서 정렬, 컴파일 오류가 많음

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

// main() must return an integer 
int main(int argc, char** argv) { 
    FILE *file; //open an existing file 
    file = fopen(argv[1], "r"); //using argv as a pointer to an array of pointers to arrays of characters 
    char *sentence = (char *) malloc(100 * sizeof(char)); //memory allocation, unsure what to use for size* 


    //fgets - reads a line from the specified stream and stores it into the string pointed to 
    //max amount set to 1000 
    while (fgets(sentence, 1000, file) != NULL) { 
     char *word; 
     int maxlen = 0; 
     char *maxW; 
     //max size of 1000 characters 
     maxW = (char *) calloc(1000, sizeof(char)); 
     word = (char *) calloc(1000, sizeof(char)); 
     word = strtok(sentence, " "); //using strtok to break sentance to token 

     //checking size of word with maxlen 
     while (word != NULL) { 
      if (strlen(word) > maxlen) { 
       maxlen = strlen(word); 
       strcpy(maxW, word); 
      } 
      word = strtok(NULL, " "); 
     } 
     printf("%s\n", maxW); //printing the max sized word 
     maxlen = 0; //reset 

     return 0; 
    } 
} 

난 단지 GCC를 사용하여 내 코드를 컴파일 창에 명령 줄을 사용하고 난 CLion를 사용하려하지만 순간에 CLion을 사용하는 방법을 알아낼 수 없습니다.

편집 : 이미지를 삭제했습니다.

+2

문장의 malloc에 ​​호출이 1,000 대신에 100을 곱한해야 하는가? – schil227

+1

텍스트의 이미지는 가져 오지 않지만 텍스트는 게시하십시오. –

+2

빌드 시스템 (또는 우리와 공유하지 않은 빌드 명령)이 깨져서 코드를 제쳐두고 (거기에 여러 가지가 결국 수정이 필요합니다). [귀하의 코드가 컴파일됩니다] (http://coliru.stacked-crooked.com/a/e2d337b637a7adf1) (이는 결코 "정확함"을 의미하지 않음). – WhozCraig

답변

0

몇 관찰있다 : 문장의

  • 최대 크기는 단어의 최대 크기보다 작다. 더 나은 상수 또는 매크로를 사용하여 이런 오타를 피하십시오.
  • argv[1] (명령 줄 매개 변수)을 사용하고 있지만 사용자가 매개 변수로 파일 이름을 보내지는 않습니다. 적절한 메시지 (argc는 매개 변수 개수)를 사용하여이 유효성을 검사하는 것이 좋습니다.
  • fopen 파일을 열려고 시도 할 수 없으면 NULL을 반환하고 코드는 확인 작업을 수행해야합니다.
  • 코드는 각 줄에 문장, 단어 및 최대 값을 할당하지만 올바르지 않으므로 이러한 할당을 주 코드의 맨 위로 이동하십시오.
  • wordsentence 이상의 포인터이므로 메모리를 할당 할 필요가 없습니다.
  • return 0;while 안에 있기 때문에 프로그램이 첫 번째 행을 읽은 다음 중지합니다.
  • 항상 freemalloc/calloc으로 할당하는 메모리.

이러한 관찰 외에도 코드가 거의 있습니다.

코드 재구성 :

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

// Using constants avoid typos 
#define MAX_SIZE 1000 

int main(int argc, char** argv) { 
    // Tokens not considered as part of a word 
    const char tokens[] = " \t\n\r,/:[]=().<>"; 
    int maxlen = 0; 
    // calloc(a,b) == malloc(a*b) 
    char *sentence = (char *) malloc(MAX_SIZE * sizeof(char)); 
    char *maxW  = (char *) calloc(MAX_SIZE, sizeof(char)); 
    char *word; 
    // try open and validate 
    FILE *file  = fopen(argv[1], "rt"); 
    if(file == NULL){ 
     printf("file '%s' cannot be opened!\n", argv[1]); 
     return 1; // !=0 means error to OS 
    } 

    while (fgets(sentence, MAX_SIZE, file) != NULL) { 
     word = strtok(sentence, tokens); 
     while (word != NULL) { 
      if (strlen(word) > maxlen) { 
       maxlen = strlen(word); 
       strcpy(maxW, word); 
      } 
      word = strtok(NULL, tokens); 
     } 
    } 
    printf("Max word='%s' (len=%d)\n", maxW, maxlen); 

    // Don't forget free memory allocated with malloc/calloc 
    free(sentence); 
    free(maxW); 

    return 0; 
} 

을 그리고 같은 프로그램 파일을 통해 실행 :

$ gcc program.c 
$ ./program program.c 
Max word='considered' (len=10) 
+0

안녕하세요, 귀하의 의견에 진심으로 감사드립니다. 좀 더 연구를 끝내고 지금 fgets를 사용하여 코드를 의도대로 작동하도록하십시오! 상수 + 무료 메모리 할당을 지적 해 주셔서 감사합니다. – Nuggets10

+0

내 게시물이 귀하의 원래 질문에 답변했다고 생각합니다. 동의 해 주시겠습니까? – WPomier

+0

할 것입니다! Stackoverflow를 사용하여 처음으로 죄송합니다! – Nuggets10