텍스트 파일에서 첫번째 짧은 단어와 두번째 짧은단어, 그리고 첫번째 긴 단어와 두번째 긴 단어를 출력하는 예제...
글쓴이: quarterhorse / 작성시간: 토, 2012/12/15 - 9:28오후
안녕하세요, 다름이 아니라, 예제를 연습하다가 질문 드립니다.
텍스트 파일에서 첫번째 짧은 단어와 두번째 짧은단어, 그리고 첫번째 긴 단어와 두번째 긴 단어를 출력하는 예제가 있는데요,
첫번째 짧은 단어와 두번째 짧은 단어를 출력해주는것은 성공했는데,
첫번째 긴 단어와 두번째 긴 단어를 출력하는것을 실패했습니다.
실제로 콘솔에서 실행해보면 shortest, second shortest만 출력됩니다... ㅠㅠ
아래는 제가 짜본 코드입니다.
#include <stdio.h> #include <string.h> #define MAXLINE 100 void copy(char from[], char to[]); char line[MAXLINE]; char shortest[MAXLINE]; char secshortest[MAXLINE]; char longest[MAXLINE]; char seclongest[MAXLINE]; main() { int len,min,secmin,max,secmax; min = 99999; secmin = 99999; max = 0; secmax = 0; FILE *fp; fp= fopen("/home/quarterhorse/program/twoshortlong/text.txt","r"); if(fp == NULL) { printf("File open for reading Fail! \n"); return 0; } while(1){ if(fgets(line,MAXLINE,fp) == NULL){ if(min < 99999) printf("shortest : %s\n", shortest); if(secmin < 99999) printf("second shortest : %s\n", secshortest); if(max > 0) printf("longest : %s\n",longest); if(secmax > 0) printf("secong longest : %s\n",seclongest); return 0; } len = strlen(line); if(len<min) { secmin=min; min=len; copy(shortest,secshortest); copy(line,shortest); } else if(len<secmin) { secmin=len; copy(line,secshortest); } if(len>max) { secmax=max; max=len; copy(longest,seclongest); } } //end of while }//end of main void copy(char from[],char to[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; }
생각대로라면 짧은거 판별해주는 로직은 잘못되있는거 같진 않은데, 긴거 판별해 주는 로직이 감이 안잡힙니다...
어떻게 수정해야 첫번째 긴 단어와 두번째 긴 단어를 출력할 수 있을까요.... ㅠㅠ
도움 주시면 정말 감사드리겠습니다....
Forums:
두 논리가 서로 다른 것 같진 않군요.
두 문장의 길이가 같은 경우 등의 예외 처리는 안 되어있습니다.
저는 이렇게 생각했습니다.
확실히...
더욱 깔끔하게 이런식으로도 나올수 있군요... 한참 제가 부족하다는 것을 다시 깨달았습니다... 친절한 답변 감사드립니다 ㅠ
댓글 달기