강의

멘토링

커뮤니티

Inflearn Community Q&A

k1bae23017551's profile image
k1bae23017551

asked

Introduction to Algorithm Problem Solving for IT Employment (with C/C++): Coding Test Preparation

31. Hydrocarbon mass

segmentation error 질문입니다.

Resolved

Written on

·

262

0

0으로 나누거나 할당된 배열의 다른범위에 참조하면 생기는 에러라고 알고 있습니다.

선생님의 소스코드와 로직은 똑같지만 저는 char 배열말고

c++, string으로 std::cin입력받았습니다.

선생님 19번째 줄과 같이

for(i = pos + 1; a[i] != '\n'; i++) 을 하였더니 이부분에서 에러가 발생했습니다. 그래서 

for(i = pos + 1; i < a.length(); i++)로 하였더니 값이 구해졌습니다.

실행환경은 MAC OS, gcc c++14 입니다.

왜그런지 알 수 있을까요?ㅠㅠ

그냥 컴파일러가 달라서 그런건가요?

#include<iostream>
using namespace std;

int main(){
    freopen("input.txt", "rt", stdin);
    int c = 0, h = 0, pos, res = 0, i;
    string a;
    cin>>a;

    if(a[1] == 'H'){
        pos = 1;
        c = 1;
    }else{
        
        for(i = 1; a[i] != 'H'; i++){
            c = c * 10 + (a[i] - 48);
        }
        pos = i;
    }

    
    if(a[pos + 1] == '\n') h = 1;
    else{
        for(i = pos + 1; a[i] != '\n'; i++){
            h = h * 10 + (a[i] - 48);
        }
    }

    res = c * 12 + h;

    cout<<res<<"\n";

    return 0;
}
C++코테 준비 같이 해요!

Answer 2

0

k1bae2301님의 프로필 이미지
k1bae2301
Questioner

아.. 죄송합니다

감사합니다.

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

k1bae23017551's profile image
k1bae23017551

asked

Ask a question