[C/C++] 자료형 변환

Onam Kwon·2022년 11월 27일
0

C/C++

목록 보기
1/12

자료형 변환

  • int에서 string
  • string에서 char
  • char에서 int
    • 아스키에선 숫자는 48을 빼줘야함.
#include <iostream>
#include <string>

using namespace std;

int main() {    
    // Convert int to string.
    int n = 10;
    string nAsString = to_string(n);

    // Convert string to char.
    for(const auto &item: nAsString) {
        cout<<item<<": "<<typeid(item).name()<<endl;
    }

    // Convert char to int.
    // In ASCII code, the numbers(digits) start from 48.
    for(const auto &item: nAsString) {
        int temp = (int)item-48;
        cout<<temp<<endl;
    }
    
    return 0;
}
~/De/D/C/P/Algorithms/A/TypeConvert main ❯ ./main.out                  22:33:48
1: c
0: c
1
0

GitHub source code

  • ex) stoi(string);
  • stoi() - Convert string to integer (function template)
  • stol() - Convert string to long int (function template)
  • stoull() - Convert string to unsigned long long (function template)
  • strtoll() - Convert string to long long integer (function)
profile
권오남 / Onam Kwon

0개의 댓글