• 검색 결과가 없습니다.

C 언어 맛보기 #5

N/A
N/A
Protected

Academic year: 2022

Share "C 언어 맛보기 #5"

Copied!
18
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

C 언어 맛보기 #5

부산대학교 전기컴퓨터공학부 김종덕 ([email protected])

본 강의 자료는 문정욱 교수님의 강의 자료를 활용하여 작성하였습니다.

(2)

강의의 목표

❖ 문자 코드의 의미와 필요성을 이해한다.

❖ C언어에서 기본으로 쓰이는 ASCII 코드에 대해 이해한다.

▪ Escape Sequence의 필요성을 이해하고 활용 방법을 익힌다

❖ 문자를 위한 자료형인 char를 이해한다.

❖ C Standard Library의 문자 입출력 함수에 대해 학습한다.

▪ Printf의 Format Conversion Specifier에 대해 이해한다.

❖ 들여 쓰기를 통한 프로그램 구조 표현 방식을 이해한다

❖ 중첩/연속 if 문의 활용법을 이해한다.

(3)

문자 코드

❖ 문자 정보의 입력과 출력

컴퓨터는 정수, 실수만 이해하고 처리할 수 있다 그러므로 사람이 사용하는 문자 정보는 이해하지 못하며 이를 처리할 능력이 없다

(4)

문자 코드

❖ 문자 코드 : 각 문자에 고유 번호(숫자)를 부여하여 표현

❖ 대표적 문자 코드 : ASCII

▪ ASCII(American Standard Code for Information Interchange)

▪ 128개의 문자를 7 비트를 사용하여 표현(8비트로 확장됨) : 2^7 = 128

• 대문자(A, B, C 등등)

• 소문자(a, b, c 등등)

• 구두점(punctuation)(마침표, 세미콜론, 쉼표 등등)

• 숫자(digit)(0에서 9까지)

• 공백 문자(‘ ’)

• 특수 문자(&, |, \ 등)

• 제어 문자

– 열복귀(carriage return), 널(null), 문서-끝-표시자(end-of-text)

• 액센트(accent)가 있는 문자

❖ 한글은?

(5)

ASCII Code

❖ 소스코드에서 문자를 표현할 때는 ‘문자’ 또는 코드 값으로 표시

❖ ‘A’ == 0x41==65, ‘z’ == 0x7A == 122

16진수Hexa

(6)

특수 문자와 Escape Sequence

❖ 이스케이프 시퀀스(escape sequence)

▪ 백슬래쉬 문자(\)로 시작하고, 다음 문자는 특별한 방식으로 해석

▪ 예를 들어 이중 인용부호 문자(") 출력: \“

▪ printf("\"Hello My\b\b\n\tWorld\"\n");

Escape Sequence 해당 문자/의미

\0, \0 NUL, Null, String Termination Char

\b, \b BS, Back Space, Erase a previous char

\t, \t HT, Horizontal Tab, Column Alignment

\n, \n LF, New Line, Line Feed

\r, \r CR, Carriage Return

\", \” “, Double Quotation

\’, \’ ‘, Single Quotation

\\, \\ Back Slash

"Hello

World"

출력 결과

(7)

char : 문자를 위한 자료형

❖ 문자 코드도 정수이므로 기존 정수형 자료형을 사용?

▪ 널리 쓰이는 ASCII 코드 값(7bits/8bits=1 Byte)을 32 bits(=4 Bytes) 크기의 int형 에 저장?  저장 공간의 낭비?

▪ 이러한 낭비를 줄이기 위한 1 Byte 문자용 자료형을 정의  char

▪ printf에서 문자 값 표시를 위한 형식 지정자  %c

• printf의 형식 지정자는 출력 형식과 관련한 것이지 대응 변수의 자료형을 특정하는 것 은 아니다. (물론 실질적/결과적으로는 연관되지만)

▪ 아래 c1, c2에 대해 출력 결과는 동일하지만 필요한 메모리 양에 차이가 있음.

#include <stdio.h>

int main(void) {

int c1=65; //='A'; =0x41;

char c2=65; //='A'; =0x41;

printf("%c, %d\n",c1,c1);

printf("%c, %d\n",c2,c2);

return 0;

}

A, 65 A, 65

입출력 결과

(8)

Tab 문자를 활용한 정렬(Alignment)

❖ 메모장(notepad.exe)을 통해 Tab 문자를 활용하여 정렬을 해보자

❖ C 언어에서도 Tab언어는 동일하게 동작

printf("abcd\tefg\n");

printf(“ab\t124\tfg\n"); abcd efg

ab 124 fg

출력 결과

(9)

C Standard Library : 문자 입출력 함수

❖ 아래 stdio.h의 함수 중 문자 입출력과 관련한 함수는 무엇일까?

▪ c 또는 char라는 접미사(suffix)를 가진 함수들. s는 string(문자열)을 위한 함수

▪ Stdin은 Standard In, stdout는 Standard Out이라는 특별한 File Stream

▪ getchar() == getc(stdin)

narrow character

Defined in header <stdio.h>

fgetc

getc gets a character from a file stream (function)

fgets gets a character string from a file stream (function) fputc

putc writes a character to a file stream (function)

fputs writes a character string to a file stream (function) getchar reads a character from stdin (function)

gets(until C11)

gets_s(since C11) reads a character string from stdin (function) putchar writes a character to stdout (function)

puts writes a character string to stdout (function) ungetc puts a character back into a file stream (function)

(10)

getchar(), putchar()

❖ Reference 확인

▪ getchar(), putchar() 함수의 return과 인자의 type을 확인하라.

▪ 아래 코드는 함수의 return 및 인자 type 관점에서 올바른가?

• 올바르지 않다면 적절하게 수정해 보라.

▪ 위 코드는 어떻게 동작하는가?

▪ 위 코드에서 while 문을 아래와 같이 변경할 때 while 문을 빠져 나오기 위해서는 어떤 문자를 어떻게 입력하여야 하나?

Ctrl-Z

• while((ch=getchar()) != EOF)

• EOF의 의미를 Reference에서 확인하라.

#include <stdio.h>

int main(void) {

char ch;

while((ch=getchar()) != '\t') { putchar(ch);

}

return 0;

}

(11)

Format Specifier of printf

❖ printf()의 Reference를 참고하여 “format”인자를 이해해보라.

Format의 conversion specification의 필수 요소는 무엇인가?

사용 가능한 format specifier에는 어떤 것이 있나?

Format specifier ‘c’에 사용 가능한 length modifier에는 무엇이 있는가?

format pointer to a null-terminated multibyte string specifying how to interpret the data. The format string consists of ordinary multibyte charact ers (except %), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the f ollowing format:

• introductory% character

• (optional)one or more flagsthat modify the behavior of the conversion:

•-: the result of the conversion is left-justified within the field (by default it is right-justified)

•+: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)

space: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if + flag is present.

•# :alternative formof the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.

•0 : for integer and floating point number conversions, leading zeros are used to pad the field instead ofspacecharacters. For integer numbers it i s ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if -flag is present.

• (optional)integer value or * that specifies minimum field width. The result is padded withspacecharacters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of t ypeint. If the value of the argument is negative, it results with the - flag specified and positive field width. (Note: This is the minimum wi dth: The value is never truncated.)

• (optional). followed by integer number or *, or neither that specifiesprecisionof the conversion. In the case when * is used, thepre cision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * i s used, the precision is taken as zero. See the table below for exact effects of precision.

• (optional)length modifierthat specifies the size of the argument

• conversion format specifier, The following format specifiers are available:

Conversion

specifier Explanation Argument type

length modifier hh h (non

e) l ll j z t L

% writes literal %. The full conversion specification must be %%. N/A N/A N/A N/A N/A N/A N/A N/A N/A

c writes a single character.The argument is first converted tounsigned char. If the lmodifier is used, the argum

ent is first converted to a character string as if by %ls with awchar_t[2]argument. N/A N/A int win

t_t N/A N/A N/A N/A N/A

(12)

Printf의 이해

❖ 다음 코드와 그 출력 결과를 확인하라.

▪ 다음 Conversion Specifier들을 세부적으로 나누고 각각의 역할을 설명하라.

• “%-+10.6d”

• “%08X”

• “% 8.2lf”

• “%-12.4le”

123456789012345678901234567890 +012367 , 0000304F

-12345.68, -1.2346e+004 2345.68, 2.3457e+003

출력 결과

#include <stdio.h>

int main(void) {

int n = 12367;

double r1 = -12345.6789123;

double r2 = 2345.6789123;

printf("123456789012345678901234567890\n");

printf("%-+10.6d, %08X\n", n, n);

printf("% 8.2lf, %-12.4le\n", r1, r1);

printf("% 8.2lf, %-12.4le\n", r2, r2);

return 0;

}

(13)

Printf 예제

❖ 다음 코드를 기초로 우측과 같은 결과를 얻도록 [1],[2],[3]의 format specifier를 작성하라.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main(void) {

int i, ranval;

printf("+---+\n");

printf("|123456|123456|12345678|\n");

printf("+---+\n");

srand(time(0));

for (i=0; i<10; i=i+1) { ranval = rand();

printf([1],ranval); // 왼쪽 정렬, 다음 | 정렬

printf([2],ranval); // 0x 시작, 대문자 16진수, 최소 4자리 printf([3],ranval); // 0o 시작, 최소 6자리, 0으로 채우기 }

printf("+---+\n");

return 0;

}

+---+

|123456|123456|12345678|

+---+

|17058 |0x42A2|0o041242|

|22143 |0x567F|0o053177|

|19806 |0x4D5E|0o046536|

|1931 |0x078B|0o003613|

|6682 |0x1A1A|0o015032|

|1755 |0x06DB|0o003333|

|23616 |0x5C40|0o056100|

|11850 |0x2E4A|0o027112|

|4592 |0x11F0|0o010760|

|10337 |0x2861|0o024141|

+---+

출력 결과

(14)

프로그램의 구조 표현

❖ 구조 파악이 어려운 소스 코드

구조를 파악하기 힘들어서 오류를 찾기 가 어렵다.

❖ 구조 파악이 쉬운 소스 코드

구조를 파악하기 쉬워서 오류를 찾기가 쉽다.

a statement (if-statement)

a statement

#include <stdio.h>

int main(void) {

int a;

scanf("%d",&a);

if (a==1)

printf("a == one\n");

printf("a == one\n");

else

printf("a == other\n");

printf("after if-stat\n");

return 1;

}

else

statement ???

Syntax Error !

#include <stdio.h>

int main(void) {

int a;

scanf("%d",&a);

if (a==1)

printf("a == one\n");

printf("a == one\n");

else printf("a == other\n");

printf("after if-stat\n");

return 1;

}

(15)

들여 쓰기(indentation)를 통한 프로그램 구조 표현

❖ Tab을 활용한 들여쓰기

C 언어에서 Tab 문자는 의미론적(Semantic)으 로는 공백 문자와 동일하다. : Python과 구별

Tab을 활용하면 공백 문자 보다 맞춤

(Alignment)을 보다 쉽게 이룰 수 있기 때문에 Indentation에 널리 쓰인다.

일반적으로 편집기마다 Tab 문자가 공백 문자 몇 개와 같게 할 지를 설정할 수 있다.

❖ 함수 내부 선언 및 문장 들

❖ if 문 안의 선언 및 문장들

#include <stdio.h>

int main(void) {

int a;

printf("Input a integer number:");

scanf("%d",&a);

scanf(“a = %d\n",&a);

return 0;

}

tab

Beginning of function:

1st column

End of function:

1st column

#include <stdio.h>

int main(void) {

int a;

printf("Input a integer number: ");

scanf("%d", &a);

if (a%2==1) {

printf("a is an odd number\n");

printf("a is an odd number\n");

printf("a is an odd number\n");

}

return 0;

}

tab tab

(16)

들여 쓰기(indentation)를 통한 프로그램 구조 표현

❖ for문 안의 선언 및 문장들 ❖ for 문 안의 if문

#include <stdio.h>

int main(void) {

int i,a;

printf("Input a integer number: ");

scanf("%d", &a);

for (i=0;i<a;++i) { printf("i=%d\n", i);

printf("a=%d\n", a);

}

return 0;

}

#include <stdio.h>

int main(void) {

int i,a;

printf("Input a integer number: ");

scanf("%d", &a);

for (i=0;i<a;++i) { printf("i=%d\n", i);

if (a%2 == 0) {

printf("a is an even number\n");

printf("a is an even number\n");

} }

return 0;

}

tab

tab

tab tab tab

(17)

중첩 if문과 연속 if문

a statement

(if-else statement)

#include <stdio.h>

int main(void) {

int a;

scanf("%d", &a);

if (a==1)

printf("a == one\n");

else {

if (a==2)

printf("a == two\n");

else

printf("a == other\n");

}

return 0;

} 이후가 a statement 이므로

Block을 만들지 않아도 된다.

#include <stdio.h>

int main(void) {

int a;

scanf("%d", &a);

if (a==1)

printf("a == one\n");

else if (a==2)

printf("a == two\n");

else

printf("a == other\n");

return 0;

}

논리적으로 동일한 코드

(18)

중첩 if 문과 연속 if 문

#include <stdio.h>

int main(void) {

int a;

scanf("%d", &a);

if (a==1)

printf("a == one\n");

else

if (a==2)

printf("a == two\n");

else

if (a==3)

printf("a == three\n");

else

if (a==4)

printf("a == four\n");

else

if (a==5)

printf("a == five\n");

else

printf("a == other\n");

return 0;

}

#include <stdio.h>

int main(void) {

int a;

scanf("%d", &a);

if (a==1)

printf("a == one\n");

else if (a==2)

printf("a == two\n");

else if (a==3)

printf("a == three\n");

else if (a==4)

printf("a == four\n");

else if (a==5)

printf("a == five\n");

else

printf("a == other\n");

return 0;

}

논리적으로 좌측과 동일한 코드이며 구조적으로 이해하기도 편리함

참조

관련 문서