c++ 문자열 처리에 관한 질문입니다

조회수 485회
입력 : 66+2+8+55+100
66
2
8
55
100

결과 : 231

이렇게 출력되는 코드를 작성하는 건데요. 아래는 제가 짠 코드입니다.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    cout << "입력 : ";
    getline(cin, s, '\n');

    int sum = 0;
    int startIndex = 0;

    while (true)
    {
        int fIndex = s.find('+', startIndex);
        int count = fIndex - startIndex;
        string part = s.substr(startIndex, count);
        cout << part << endl;
        sum += stoi(part);
        startIndex = fIndex + 1;

        if (fIndex == -1)
            break;
    }
    cout << endl << "결과 : " << sum << endl;
}

근데 교재에서는 위 코드에서 while문만 다르게 썼는데

while (true)
    {
        int fIndex = s.find('+', startIndex);

        if (fIndex == -1)
        {
            string part = s.substr(startIndex);

            if (part == " ")
                break;

            cout << part << endl;
            sum += stoi(part);
            break;
        }
        int count = fIndex - startIndex;
        string part = s.substr(startIndex, count);
        cout << part << endl;
        sum += stoi(part);
        startIndex = fIndex + 1;
    }

이렇게 썼더라구요. 저는 if문 안에 그냥 break;만 썼는데 저렇게 하는것과 실행했을때 결과는 똑같아서 무슨 차이인가요??

  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)