[getchar()]
int getchar(void);
getc(stdin);
// 위의 getc(stdin) 함수는 getchar() 함수와 기능정으로 동일하다.
[내용]
stdin(표준입력장치)으로부터 문자 하나를 읽는 함수이다.
만약 표준입력장치의 버퍼가 비워있으면 사용자의 입력을 기다리며
버퍼에 문자가 있으면 해당 문자를 버퍼에서 빼서 곧바로 반환한다.
파라미터 : 없음
반환값 : 성공할 경우 획득한 문자 하나를 반환하며, 실패할 경우 EOF를 반환한다.
만약 파일의 끝에 도달하여 EOF가 반환될 경우 feof() 함수를 통해 조건을 체크할 수 있고,
그 밖의 다른 오류에 의해 EOF를 반환될 경우 ferror()함수를 통해 조건을 체크한다.
다음은 해당 문법을 통한 예제이다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int ch;
while ((ch = getchar()) != EOF)
{
printf("%c", (char)ch);
}
if (feof(stdin))
{
puts("파일의 끝에 도달");
}
else if (ferror(stdin))
{
perror("getchar()");
fprintf(stderr, "getchar() %s의 #%dline에서 오류 발생하여 실패", __FILE__, __LINE__ - 12);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
[실행화면]
(참고로 ^Z는 Ctrl+Z 이다.)
https://en.cppreference.com/w/c/io/getchar
getchar - cppreference.com
Reads the next character from stdin. Equivalent to getc(stdin). [edit] Parameters (none) [edit] Return value The obtained character on success or EOF on failure. If the failure has been caused by end-of-file condition, additionally sets the eof indicator (
en.cppreference.com
[putchar()]
int putchar(int ch);
[설명]
표준출력장치(stdout)에 하나의 문자를 쓴다.
좀 더 부연 설명을 하자면 표준출력장치의 메모리(버퍼)에 하나의 문자를 쓰는데
쓰기 전에 unsigned char 타입으로 변환된다.
char ch;
putc(ch, stdout);
위의 putc(ch, stdout)함수는 putchar(ch) 함수와 기능적으로 동일하다.
[매개변수]
int ch : 문자 하나
[반환값]
성공 시 쓴 문자 하나 반환
실패 시 EOF 반환 (오류 발생 시 ferror()로 처리 가능)
[예제]
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int ret_code = 0;
// a ~ z 출력,
for (char c = 'a'; (ret_code != EOF) && (c <= 'z'); ++c)
{
ret_code = putchar(c);
}
if (ret_code == EOF)
{
// 표준출력장치(stdout)에서 오류 발생 시 처리
if (ferror(stdout))
{
fprintf(stderr, "putchar() failed in file %s at line # %d\n", __FILE__, __LINE__ - 8);
perror("putchar()");
exit(EXIT_FAILURE);
}
}
putchar('\n');
int r = 0x1070;
printf("\n0x%x\n", r);
r = putchar(r);
printf("\n0x%x\n", r);
return 0;
}
[실행 결과]
0x1070은 10진수로 4208이다.
int putchar(int ch) 함수는 버퍼에 쓰기 전 매개변수인 ch를 unsigned char 타입으로 변환하여 쓴다.
따라서 4208을 아스키 코드표의 값으로 변환해보면
4208 mod 128 = 112이므로
112 == 0x70 == 'p' 이다.
https://en.cppreference.com/w/c/io/putchar
'c언어' 카테고리의 다른 글
5. 기초 연산자 (0) | 2023.05.27 |
---|---|
4. 기본 입출력 함수 (3) | 2023.05.27 |
3. 기본 이론과 개발 도구의 활용 연습문제 (0) | 2023.04.30 |
2. C언어 입문 연습문제 (0) | 2023.04.26 |
[문법] fgets() (0) | 2023.04.19 |