본문 바로가기

C-Language/String in out to STDOUT

String in/out to STDOUT

C언어에서 문자열 입/출력 예

#include <stdio.h>
#include <string.h>
/*
키보드(표준입력, stdin스트림)로부터 문자열을 입력하는 함수들
gets() : The gets() function reads characters from stdin and loads them into str, until a newline or EOF is reached.
The newline character is translated into a null termination.
The return value of gets() is the read-in string, or NULL if there is an error.
Note that gets() does not perform bounds checking, and thus risks overrunning str.
For a similar (and safer) function that includes bounds checking, see fgets().

fgets() : The function fgets() reads up to num - 1 characters from the given file stream and dumps them into str.
The string that fgets() produces is always NULL- terminated.
fgets() will stop when it reaches the end of a line, in which case str will contain that newline character.
Otherwise, fgets() will stop when it reaches num - 1 characters or encounters the EOF character.
fgets() returns str on success, and NULL on an error.

scanf() : 공백문자로 구분된 한개의 문자열을 가져온다
fscanf() :

puts() :

fputs() :

printf() :

fprintf() :

*/

int main(int argc, char * argv[]) {

 char dest[20], temp[2];
 int count = 0;
 
 puts("문자열을 입력하고 엔터를 치세요. 종료(x)");

 while(1) {
  printf("문자열 입력:");

  gets(dest);
  if(strcmp(dest,"x")==0) break;

  printf("\n입력된 문자열="); puts(dest);

  fflush(stdin);
 }
 printf("gets()끝--------------------scanf()시작\n");

 fflush(stdin);
 while(1) {
  printf("문자열 입력:");
  count = scanf("%s", dest);
  if(strcmp(dest,"x")==0) break;

  printf("\n입력된 문자열=%s\n",dest);
  fflush(stdin);
 }

 printf("scanf()끝--------------------fscanf()시작\n");

 fflush(stdin);
 while(1) {
  printf("문자열 입력:");
  count = fscanf(stdin, "%s", dest);
  if(strcmp(dest,"x")==0) break;

  fprintf(stdout, "\n입력된 문자열=%s\n",dest);
  fflush(stdin);
 }

 printf("fscanf()끝--------------------fgets()시작\n");

 fflush(stdin);
 /* fgets()함수는 한 라인을 읽을 때 개행문자도 포함하여 읽어온다
 *  그러므로 위와같은 같은 방법으로는 루프를 종료할 수 없다 */

 while(1) {
  printf("문자열 입력:");
  fgets(temp, sizeof(temp), stdin);    //개행문자('\n') 포함됨

  strncpy(dest,temp,strlen(temp)-1);  //개행문자 제검됨
  dest[strlen(temp)-1] = '\0';           //'\0' 추가함

  if(strcmp(dest,"x")==0) break;
  printf("%s, len=%d\n", dest, strlen(dest));

  printf("\n입력된 문자열=");   fputs(dest,stdout);
  fflush(stdin);
 }
}