언어 공부/C++
[C++] stoi, stof, atoi, c_str
수기
2022. 5. 21. 20:25
stoi : string ➡️ int
stof : string ➡️ float
atoi : char* ➡️ int
stoi, stof 사용 시 #include <string> 헤더 추가
atoi 사용 시 #include <cstdlib> 헤더 추가
문자열 ABC 중 알파벳을 하나씩 숫자로 표현하는 법 ( string to char )
string t = "ABC";
for(int i=0;i<t.length();i++) {
string a = t.substr(i,1); //문자를 1개씩 끊기
const char *c = a.c_str(); //string을 char로 변환
int num = *c - 64; //char를 숫자형태로 변환 ( A = 1 , B = 2... )
}
문자 1개는 - '0' 으로 표현 하면 된다!
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
int test_case;
string T;
cin >> T;
int sum = 0;
int T_len = T.length();
for(test_case = 0; test_case < T_len; ++test_case)
{
sum += T.back() - '0';
T.erase(T.end()-1);
}
cout << sum;
return 0;
}