C 정리(중간대비)

dev_butler·2023년 4월 9일

c에서 살아남기

목록 보기
3/5

2주

  • 리터럴 상수
  • #define
  • const 상수
%%writefile test.cpp
#include <stdio.h>

#define MAX_NUM 999 // #define을 사용한 매크로 상수 선언은 '='를 사용하지 않는다

int main()
{
    const char TEST_CHAR = 'c';  //const 상수에선 '='가 필요하다
    
    printf("MAX_NUM = %d\n", MAX_NUM);
    printf("TEST_CHAR = %d\n", TEST_CHAR);
    
    return 0;
!g++ test.cpp; ./a.out

: 실행결과
MAX_NUM = 999
TEST_CHAR = 99

  • 변수
    변수 선언 : 데이터타입 변수명;
    초기화 : 선언할때 리터럴 상수 값 할당
##writefile test.cpp
#include <stdio.h>

int main()
{
    int a;  //변수 선언
    a = 9;  //변수에 값 할당
    
    int num = 9;  //변수(선언+할당)=변수 초기화
    
    int n[3] = {1, 3, 5};
    int m[9] = {0, };

3주

  • 출력
    printf()
    숫자 정렬 시 %3d, %-3d(왼쪽 정렬), %5.2f(실수)

  • 입력
    scanf() - 원하는 자료형의 변수로 입력받는다. 형태 : (&변수, 주소)
    getc(입력받을대상) - 문자 한개 입력받는다
    getchar() - get()입력받을 대상이 stdin인 경우 대체 표현

input
 three values: 9 1.56 x
 a sentence: hello world
 
output
 "9          "
 "1.56       "
 "x          "
 "hello world"
#include <stdio.h>

int main()
{
    int n1;
    float n2;
    char ch, sentence[100];
    
    printf("inputs\n");
    printf("   three values: ");
    scanf("%d %f %d", &n1, &n2, &ch);
    getchar();  //엔터값 받아서 무시할 용도
    
    printf("   a sentence: ");
    fgets(sentence, 1024, stdin);
      //1024길이만큼 받고, 표준 입력 디바이스에서 값 받을 것
      
    printf("\n\noutputs\n");
    printf("  \"%d-11d\"\n", n1);
    printf("  \"%-11.2f\"\n", n2);
    printf("  \"%-11c\"\n", ch);
    printf("  \"%s\"\n", sentence);
    
    return 0;
}
  • & + 변수
    &변수명 : 메모리에서 변수의 위치를 뜻한다.
    • 주소값도 %p로 가능
    • 배열일땐 '&변수명'만 사용 가능
%%writefile test.cpp
#include <stdio.h>

int main()
{
    int x = 3;
    
    printf("x = %d\n", x);
    printf("x's address = %p\n", &x);
    printf("int size = %ld bytes\n", sizeof(int));
    
    return 0;
!g++ test.cpp ./a.out

: 실행결과
x = 3
x's address = 0x7ffdc4d055c4
int size = 4 bytes

4주

  • fopen
    : fclose로 사용 끝내야함
  • fprintf()
    : fprintf(파일객체, "내용", [변수]);
%%writefile test.cpp
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp = fopen("input.txt", "w");
    
    int n = 9;
    char buf[100] = "hello world";
    
    fprintf(fp, "%s %d \n", buf, n);
    fprintf(fp, "file output test\n");
    
    fclose(fp);
    
    return 0;
}
!g++ test.cpp; ./a.out
!cat input.txt

: 실행결과
hello world 9
file output test

  • fgets()
    : 파일 줄 수 계산
    fp 위치 처음으로 이동
    파일 복사
    특정 라인에 내용 추가

0개의 댓글