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;만 썼는데 저렇게 하는것과 실행했을때 결과는 똑같아서 무슨 차이인가요??
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력