U E D R , A S I H C RSS

이영호/문자열검색

출제자의 뜻이 strstr함수를 이용하는 것이 아니라
strstr, strcase, strspn등과 비슷한 함수를 제작하는 것이었다면 이 답은 틀렸다.

~cpp 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

// while 고치기 귀찮다. while을 무한 루프 돌리고 Ctrl-C를 정상적인 종료로 바꿔 끝내자.
void handler(int sig)
{
        fprintf(stderr, "\n프로그램을 종료합니다.\n");
        exit(0);
}
//


int main()
{
        FILE *fp;
        char x[40] = "His teaching method is very good.";
        char buf[10];
        char *loc;


// signal handling
        struct sigaction act;

        act.sa_handler = handler;
        sigemptyset(&act.sa_mask);
        act.sa_flags = 0;

        sigaction(SIGINT, &act, 0);
//


        if((fp = fopen("result.out", "w")) == NULL)
                fprintf(stderr, "fopen() error: result.out\n"), exit(-1);

        while(1){
                fprintf(fp, "자료 -> %s\n", x);
                fprintf(fp, "찾을 문자열 -> ");

                printf("찾을 문자열 -> ");
                fgets(buf, sizeof(buf), stdin);         // 문자열이라고 했으니 space를 포함한다.
                buf[strlen(buf)-1] = '\0';              // stream으로 받은 \n을 제거한다.
                fprintf(fp, "%s\n", buf);

                if((loc = strstr(x, buf)) == 0)
                        fprintf(fp, "Not Found!\n");
                else
                        fprintf(fp, "first found -> %d\n", loc-x);
                fflush(fp);
        }

        fclose(fp);
        return 0;
}

~cpp 
// result.out

자료 -> His teaching method is very good.
찾을 문자열 -> method
first found -> 13
자료 -> His teaching method is very good.
찾을 문자열 -> test
Not Found!
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:30:32
Processing time 0.0072 sec