ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1068) N
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (181) N
      • Unreal (69)
      • Unity (101) N
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 언리얼
  • 문자열
  • 유니티
  • 티스토리챌린지
  • 클래스
  • 백준
  • 배열
  • 프로그래머스
  • c#
  • 파이썬
  • 알고리즘
  • 그래픽스
  • 포인터
  • 오블완
  • string
  • C++
  • SQL
  • Unity
  • C
  • 함수

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

[C++] stoi, stof, stol, stod 함수에 대해서 (string to int), 문자열 > 특정 타입
프로그래밍 언어/C++

[C++] stoi, stof, stol, stod 함수에 대해서 (string to int), 문자열 > 특정 타입

2023. 7. 20. 10:50

1. C++에서 string 타입의 문자열을 숫자로 바꾸는 함수들의 이름.

▼ C++11 부터 아래 함수들을 사용할 수 있다.

stoi = string to int

stof = string to float

stol = string to long

stod = string to double

stoul = string to unsigned int

stoll = string to long long

stoull = string to unsigned long long

stold = string to long double

2. C++ stoi, stof, stol, stod 함수 원형과 매개변수가 뜻하는 것

▼ 함수 원형

1) 정수형

int stoi(const string& str, size_t* idx = 0, int base = 10)

long stol(const string& str, size_t* idx = 0, int base = 10)

 

2) 실수형

float stof(const string& str, size_t* idx = 0)

double stod(const string& str, size_t* idx = 0)

 

▼ 매개변수가 뜻하는 것들

함수원형1 : int stoi(const string& str, size_t* idx =0, int base = 10);

함수원형2 : float stof(const string& str, size_t* idx = 0);

 

첫번째 인자 : const string& str: 변경할 문자열이 들어가게 된다. 문자열 복사의 비용이 들어가지 않도록 & (reference)를 이용해서 넘기게 된다. 또한 함수 내부에서 변경이 일어나지 않음을 보장하기 위해서 const 상수 취급해서 넘기게 된다.


두번째 인자 : size_t* idx = 0: 두번째는 포인터 타입이고 맨 첫번째 부터 숫자가 아닌 부분까지 해서 그부분의 포인터를 걸러준다. 세번째 인자까지 사용하는데, 두번째 인자는 사용하지 않겠다 하면 nullptr을 넣으면 된다.

 

세번째 인자 : int base = 10 (정수형에만 존재): base 는 진수를 뜻하는 것이다. default가 10으로 되어있다는건 10진수가 기본이라는 뜻이고 string 안에 있는 숫자의 표현이 어떤것이다 라고 base 를 통해서 알려주는 것 이다.: binary (2진수)이라면 2를 넣고: octal (8진수)이라면 8을 넣고: decimal (10진수)는 기본이니까 넣지 않아도 된다. hexadecimal (16진수)이라면 16을 넣으면 된다.

예제

//[C++] stirng to integer example1
//BlockDMask
 
#include<iostream>
#include<string> //need this
using namespace std;
int main(void)
{
    string str_i = "22";
    string str_li = "2144967290";
    string str_f = "3.4";
    string str_d = "2.11";
 
    //int i = str_i;    //error
    int i       = stoi(str_i);
    long int li = stol(str_li);
    float f     = stof(str_f);
    double d    = stod(str_d);
 
    //C++ cout
    cout << "stoi : " << i    << endl;
    cout << "stol : " << li  << endl;
    cout << "stof : " << f    << endl;
    cout << "stod : " << d    << endl;
 
    cout << endl;
    //C, C++ printf
    printf("stoi : %d\n", i);
    printf("stol : %ld\n", li);
    printf("stof : %f\n", f);
    printf("stod : %lf\n", d);
 
    cout << endl;
    system("pause");
    return 0;
}

C++ stoi, stol, stod, stof 함수 예제2 (매개변수들을 이용한 응용 사용법)

//[C++] stirng to integer example2
//BlockDMask
 
#include<iostream>
#include<string> //need this
using namespace std;
int main(void)
{
    //mixed string
    string str1 = "33BlockDMask";
 
    //test1
    int num1 = stoi(str1);
    cout << "test1. stoi(str1);" << endl;
    cout << " - str1 : " << str1 << endl;
    cout << " - num1 : " << num1 << endl;
    cout << endl;
 
    //test2
    size_t sz;
    int num2 = stoi(str1, &sz);
    cout << "test2. stoi(str1, &sz);" << endl;
    cout << " - str1 : " << str1 << endl;
    cout << " - num2 : " << num2 << endl;
    cout << " - sz : " << sz << endl;
    cout << " - str1[sz] : " << str1[sz] << endl;
    cout << " - str1.substr(sz) : " << str1.substr(sz) << endl;
 
    cout << endl;
    //test3
    string str2 = "";
    cout << "test3. stoi(str2, nullptr, base);" << endl;
    
    //string binary -> int
    str2 = "1110";
    cout << " - stoi(1110, nullptr, 2) : " << stoi(str2, nullptr, 2) << endl;
    
    //string oct -> int
    str2 = "014";
    cout << " - stoi(014 , nullptr, 8) : " << stoi(str2, nullptr, 8) << endl;
 
    //string hex -> int
    str2 = "0x14";
    cout << " - stoi(0x14, nullptr, 16) : " << stoi(str2, nullptr, 16) << endl;
    
    cout << endl;
    system("pause");
    return 0;
}

출처 : [C++] stoi, stof, stol, stod 함수에 대해서 (string to int) (tistory.com)

저작자표시 (새창열림)

'프로그래밍 언어 > C++' 카테고리의 다른 글

[C++] string(문자열) 클래스 변환(atoi, c_str()) 등 정리  (0) 2023.07.20
[C/C++] atoi, atof, atol 함수 (char* to int), 문자열 > 값 타입  (0) 2023.07.20
[C++] to_string 함수에 대해서, 특정 타입 > 문자열  (0) 2023.07.20
C++ 전처리기로 코드 영역 블록 설정  (0) 2023.03.25
C++ std::shared_ptr로 thread safe callback 구현하기  (0) 2023.01.08
    '프로그래밍 언어/C++' 카테고리의 다른 글
    • [C++] string(문자열) 클래스 변환(atoi, c_str()) 등 정리
    • [C/C++] atoi, atof, atol 함수 (char* to int), 문자열 > 값 타입
    • [C++] to_string 함수에 대해서, 특정 타입 > 문자열
    • C++ 전처리기로 코드 영역 블록 설정
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바