Baekjoon 11720

윤동환·2022년 11월 30일
0

Algorithm

목록 보기
12/54
post-thumbnail

내가 작성한 코드

#include <iostream>
#include <string>

using namespace std;

int main() {
    int count = 0;
    string all;
    int sum = 0;

    cin >> count >> all;

    for (int i = 0; i < count; ++i) {
        sum += all[i] - '0';
    }

    cout << sum << endl;
    return 0;
}

아쉬운점
all[i] - '0'처럼 문자열 0에대한 ascii code 값을 빼주어 숫자로 변환하는 방식이 아닌 stoi 함수를 사용하여 작성하지 못한 점이다.

그 이유는

andidate function not viable: no known conversion from 
'std::basic_string<char>::value_type' 
(aka 'char') to 'const std::string' 
(aka 'const basic_string<char>') 
for 1st argument

이러한 에러가 발생하였기 때문인데 string 자체의 변수는 stoi로 변환이 가능하였지만 string[i]의 경우 char판별로 되어 stoi가 가능하지 않았다.

해서 atio를 사용하여 string[i]를 변화시켜보려 하였으나

candidate function not viable: no known conversion from 
'char' to 'const char *' for 1st argument; take 
the address of the argument with &int atoi(const char *);

이러한 에러가 발생하였다.
atoi는 문자의 직접적 변화를 주어야 하므로 주소값을 넘겨주어야 했다. 해서 참조자를 넘겨주어 해결하였다.

최종 코드

#include <iostream>
#include <string>

using namespace std;

int main() {
    int count = 0;
    string all = "";
    int sum = 0;

    cin >> count >> all;
    for (int i = 0; i < count; ++i) {
        const char k = all[i];
        sum += atoi(&k);
    }

    cout << sum << endl;
    return 0;
}
profile
모르면 공부하고 알게되면 공유하는 개발자

0개의 댓글