본문 바로가기

C++/기초

[C++] 문자열

컴퓨터는 모든 데이터를 1개씩 처리

문자열은 메모리에 첫 문자 주소를 나타내는 주소상수

1. 문자(Char)

  1. 초기화 외에는 strcpy() unsafe 함수를 이용 ex) strcpy(a,"TEST");
    unsafe 때문에 strncpy_s(a, size, "TEST", 100);~ ~를 사용했음
  2. 아래 배열에서 사용하는 방법과 크게 다르지 않아 코드 생략

2. 배열(Array)

  1. 크기가 고정되어 변화가 되지 않음
void main() {
    int size;
    cout << "input size : ";
    cin >> size;

    char* arr = new char[size];
    /*
    * 작성일자 : 23.12.19
    * 이슈사항 : char a[size]; 의 경우 size가 상수가 아니므로 선언되지 않음
    * 해결방안 : 아직 vecter를 배우지 않았으므로, 가변 길이 배열을 만들기 위해 동적할당
    * 참고사항 : https://qna.programmers.co.kr/questions/6708/%EB%B0%B0%EC%97%B4%EC%9D%98-%ED%81%AC%EA%B8%B0%EB%A5%BC-%EB%B3%80%EC%88%98%EB%A1%9C-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0
    */

    if (size >= 5) {
        strncpy_s(arr, size, "TEST", 100);
        /*
        * 작성일자 : 23.12.19
        * 이슈사항 : unsafe(strcpy, strncpy)
        * 해결방법 : strncpy_s 사용
        * 참고사항 :
        _ACRTIMP errno_t __cdecl strncpy_s(
        _Out_writes_z_(_SizeInBytes) char*       _Destination,
        _In_                         rsize_t     _SizeInBytes,
        _In_reads_or_z_(_MaxCount)   char const* _Source,
        _In_                         rsize_t     _MaxCount
        );
        */
        cout << arr << endl;

        for (int i = 0; i < size; i++) {
            cout << *arr << endl;
            arr += 1;
            // *arr 할 경우 "T"+1 이 되므로 T,U,V . . .이 출력됨
            // arr +=1 의 경우 주소+1이 되므로 다음문자를 출력하는 것으로 보임
        }
        arr -= size;
        /*
        * 작성일자 : 23.12.19
        * 이슈사항 : 중단점 명령(__debugbreak() 문 또는 유사한 호출)이 ?.exe에서 실행되었습니다.
        * 해결방안 : arr 는 주소상수라고 하였으므로 더했던만큼 다시 빼줌
        */
    }
    else {
        cout << "size is less than 5 " << endl;;
    }


    delete[] arr;
}

3. 2D(two-dimensional) array

#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string.h> //strncpy_s를 위해 사용
#include <assert.h> //assert를 위해 사용

using namespace std;


void main() {
    // 배열을 선언하는 경우
    char array2D[2][3] = { "TE","ST" };
    for (int i = 0; i < 2; i++) {
        assert(array2D[i] != NULL);
        cout << array2D[i] << endl;
    }

    // 배열의 값을 변경하는 경우
    strncpy_s(array2D[0], sizeof(array2D[0]), "AB", 3);
    strncpy_s(array2D[1], sizeof(array2D[1]), "CD", 3);
    for (int i = 0; i < 2; i++) {
        assert(array2D[i] != NULL);
        cout << array2D[i] << endl;
    }

    // 배열의 값을 입력받는 경우
    cout << "array2D[0] : ";
    cin.get(array2D[0], 3);
    //fflush(stdin);
    cin.get();
    cout << "array2D[1] : ";
    cin.get(array2D[1], 3);
    for (int i = 0; i < 2; i++) {
        assert(array2D[i] != NULL);
        cout << array2D[i] << endl;
    }
}

4. 포인트 변수: 문자열 참조

#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string.h> //strncpy_s를 위해 사용
#include <assert.h> //assert를 위해 사용

using namespace std;

void test(char* ptrA, const char* ptrString) {
    assert(ptrString != NULL);
    strncpy_s(ptrA, sizeof(ptrA), ptrString, 20);
    cout << ptrString << endl;
}


void main() {
    // 문자열 주소 저장 방법 1
    const char* ptrTest1 = "TE";
    cout << ptrTest1 << endl;
    /*
    * 작성일자 : 23.12.19
    * 이슈사항 : C2440 '=': 'const char [3]'에서 'char *'(으)로 변환할 수 없습니다.
    * 해결방안 : char *ptrTest1 = "TE"; 
             -> const char *ptrTest1 = "TE";
    * 참고사항 : https://blog.naver.com/tipsware/221242721220
    */

    // 문자열 주소 저장 방법 2
    const char *ptrTest2;
    ptrTest2 = "ST";
    cout << ptrTest2 << endl;

    char testString[20];
    test(testString, "ABC");
    /*
    * 작성일자 : 23.12.19
    * 이슈사항 : C2664 'void test(char *,char *)': 인수 2을(를) 'const char [4]'에서 'char *'(으)로 변환할 수 없습니다.
      위와 같은 에러이나 발생지점이 다름, 매개변수에도 const를 붙여야 실행됨
    * 해결방안 : void test(char* ptrA, char* ptrString) {
              -> void test(char* ptrA, const char* ptrString) {
    * 참고사항 : https://udpark.tistory.com/40
    */

    // 동적할당
    char* ptr;
    int ptrsize(10);
    ptr = new char[ptrsize];

    strncpy_s(ptr, sizeof(ptr), "TEST", ptrsize);
    cout << ptr << endl;

    cin.get(ptr, ptrsize);
    cout << ptr << endl;

    delete[] ptr;
}