배움 저장소
홍정모의 따라하며 배우는 C언어 8 문자 입출력과 유효성 검증 본문
8.1 입출력 버퍼
buffer를 사용하지 않는 입력
#include <conio.h> // Only Windows, _getch(), _getche()
int main()
{
char c;
while ( (c = _getche()) != '.') // 'e' for echo
putchar(c);
}
Output
hheelllloo wwoorrlldd
buffer를 사용하지 않으면 위와 같이 출력된다. 위 코드는 아래 그림의 첫 번째 사례이다.
while( getchar() != '/n' ); 일 때 입력값은 buffer에 저장된다. '/n'을 만나거나 buffer가 저장할 수 있는 용량을 넘어서면 이때까지 저장된 자료를 반환하고 다시 값을 입력받는다.
8.2 파일의 끝
char c;
while(1)
{
c = getchar();
printf("%d\n", c);
if(c == EOF)
break;
}
해당 코드를 실행한 이후 "Ctrl + Z" Shortcut을 입력하면 프로그램이 종료된다. 이 때 Ctrl+Z를 End of File 줄여서 EOF라고 부른다.
EOF는 값 -1로 입력이 끝났음을 표시한다. 사용자가 컴퓨터와 정보를 주고받는 Stream 개념에서 EOF는 언제 입력이 끝났는지를 알려줄 수 있다.
8.3 입출력 방향 재지정
Input / Ouput Redirection
/* 입력값을 txt파일에서 받아온다 */
D://{FileDirectory}//builded.exe < input.txt
/* 결과값을 지정한 txt파일에 저장한다 */
D://{FileDirectory}//builded.exe > output.txt
/* input.txt파일에서 입력값을 받아오고 결과값을 output.txt에 저장한다. */
D://{FileDirectory}//builded.exe < input.txt > output.txt
/* 결과값을 기존에 있던 txt 파일 뒤에다 덧붙인다. */
D://{FileDirectory}//builded.exe >> output.txt
Copy and PipeLine
/* copy file */
copy builded.exe copied.exe
/* result of first execution will be
inserted as input at second execution */
copied.exe | builded.exe
8.4 사용자 인터페이스는 친절하게
char c;
while(1)
{
c = getchar();
printf("%c\n",c);
while(getchar() != '\n')
continue;
}
첫 번째 getchar( ) 함수는 입력값을 여럿 받아 buffer에 저장한다. 두 번째 getchar( )는 사용자에게 값을 입력받지 않고 buffer 안에 있는 값이 줄바꾸기 기호가 될 때까지 꺼낸다.
8.5 숫자와 문자를 섞어서 입력받기
void printRepeatly(char c, int col, int row);
int main()
{
char c;
int cols, rows;
printf("Input one character and two intgers for rows and columns\n");
while ((c = getchar()) != '\n')
{
scanf("%d %d", &rows, &cols);
while (getchar() != '\n') continue;
printRepeatly(c, rows, cols);
printf("Input one character and two intgers for rows and columns\n");
printf("Press Enter to quit\n");
}
}
void printRepeatly(char c, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; ++j)
putchar(c);
putchar('\n');
}
}
scanf( ) 함수는 자료형에 맞지 않는 데이터가 들어오면 종료된다. 예를 들어 scanf( ) 함수 내부에서 character 자료형을 입력받을 경우 '\n', 'space'는 buffer에 입력된다. 만약 scanf( ) 함수 내부에서 int 자료형을 입력받을 경우 '\n', 'space'는 입력되지 않고 무시된다.
8.8 메뉴 만들기 예제
void count(void);
void getchoice(void);
int main()
{
int c;
while( (c = get_choice()) != 'q')
{
switch(c)
{
case 'a':
printf("This is your programe\n");
break;
case 'b':
putchar('\a');
break;
case 'c':
printf("Insert some input for Counting\n");
count();
break;
default:
printf("Error with %d.\n", c);
exit(1);
break;
}
}
return 0;
}
void count()
{
int input;
char c;
while(scanf("%d", &input) != 1)
{
while( (c = getchar()) != '\n')
putchar(c);
printf(" is Invalid input, Try it again\n");
}
while(getchar() !='\n')
continue;
for(int i=input; 0<i; --i)
printf("%d ",i);
printf("\n");
}
int get_choice()
{
int i;
while(1)
{
printf("\nInsert your Input\n");
printf("a. Print Message\t b. sound Beep\n");
printf("c. Counting Numbers\t q. Quit\n");
i = getchar();
while( getchar() != '\n')
continue;
if(i=='q' || i=='a' || i=='b' || i=='c')
{
break;
}
printf("Please Try it again\n");
}
return i;
}
while[ getchar( ) != '\n' ] continue; 함수를 이용해서 buffer를 비워주지 않으면 그 다음 반복문이 시작되어 getchar( ) 함수가 실행될 때 입력값을 받지않는다(buffer 안의 값을 꺼냄). 입력 수('\n'포함)만큼 입력 값을 받지않고 실행된다.
8.9 텍스트파일 읽기
int c;
FILE *file = NULL;
char fileName[] = "test.txt";
file = fopen(fileName, "r");
if(file == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
while( (c = getc(file))!=EOF)
putchar(c);
fclose(file);
'Programming Language > C' 카테고리의 다른 글
홍정모의 따라하며 배우는 C언어 10.배열과 포인터 (0) | 2021.11.22 |
---|---|
홍정모의 따라하며 배우는 C언어 9 함수 (0) | 2021.11.20 |
홍정모의 따라하며 배우는 C언어 7 분기 (0) | 2021.11.15 |
홍정모의 따라하며 배우는 C언어 6 반복문 (0) | 2021.11.12 |
홍정모의 따라하며 배우는 C언어 5 연산자, 표현식, 문장 (0) | 2021.11.11 |