본문 바로가기
C 언어

C언어 scanf 로 한 줄 읽어 들이기

by treeCoder 2021. 2. 6.

C언어 scanf 로 한 줄 읽어 들이기 예제이다. fgets로 읽어들이는 방법도 있지만 여기서는 scanf를 활용하는 방법을 소개한다. 중간에 있는 space나 tab도 읽어들인다. enter key를 치면 종료한다.

#include <stdio.h>

int main() {

   char test[40];
   int keepGoing= 1;

   while( keepGoing != 0 ) {
           puts("Enter your address. (type \'.end\' to finish.)");
           scanf("%39[^\n]", test); while( getchar() != '\n');

           if( test[0] == '.' && test[1] == 'e'  && test[2] == 'n'  && test[3] == 'd'  ) {
                keepGoing = 0;
           } else 
               printf("[%s]\n", test);
    }
    return 0;
}

 

실행 결과는 아래와 같다.

 

댓글