C++ 스트링클래스 연산관련 질문입니다.
글쓴이: 익명 사용자 / 작성시간: 일, 2017/04/16 - 11:38오후
4+125+4+77+102등으로 표현된 덧셈 식을 문자열로 입력받아 계산하는 프로그램작성입니다.
#include<iostream>
#include<string>
using namespace std;
int main() {
string s;
cout << "7+23+5+100+25와 같이 덧셈 문자열을 입력하세요." << endl;
getline(cin, s, '\n');
int sum = 0; //sum과 index의 변수를 0이라고 선언해준다.
int startIndex = 0;
while (true) { //반복 while문을 이용해서 반복을시킨다.
int fIndex = s.find('+', startIndex); // find 문자열검색으로 startIndex 변수 선언 0 부터 +를 찾는다.
if (fIndex == -1) { //만약 -1발견할 수 가없다면...
string part = s.substr(startIndex); //part 스트링열에서 substr은 문자열 발췌이므로 startIndex 변수선언 0부터 발췌를한다.
if (part == "") break; //반복문의 브레이크 하고 part를 탄생시킨다. //만약 빈 블랭크가 있다면 거기서 브레이크로 반복문을벗어난다
cout << part << endl; // part는 stoi로 문자열에서 숫자로 변하고
sum += stoi(part); //연산자가된다.
break;
}
int count = fIndex - startIndex;
string part = s.substr(startIndex, count);
cout << part << endl;
sum += stoi(part);
startIndex = fIndex + 1; //다음 계산을 위해 앞으로 가기
}
cout << "숫자들의 합은" << sum;
return 0;
}여기서 +연산 외에도 -연산을 하는 방법을 찾고있습니다.
+와 -를 구분하기 위해서 if문이용 비교를 이용했습니다. 여기까지는 좋았습니다
그러나 -가 나오고 +가 나온뒤 다시 -가 나왔을 때 구분을 하지 못하는 에러가 발생했습니다.
+연산이 되어야 할 부분에서 -연산이 되는가 하면 역으로 이루어지는 경우도 있었습니다.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cout << "7+23+5+100+25와 같이 덧셈 문자열을 입력하세요." << endl;
getline(cin, s, '\n');//문자열 입력
int result = 0;
int startIndex = 0;
while (1) {
int Addindex = s.find('+', startIndex); //+ 문자열검색
int Subindex = s.find('-', startIndex); //- 문자열 검색
if (Addindex < Subindex) { // +문자열 검색 인덱스 값이 작을때
if (Addindex == -1) { // s 스티링 배열에서 +를 못찾을 경우 //만약 찾은경우 아래 if문으로 이동
string part = s.substr(startIndex); // s스트링 내 선언한 stringIndex 변수부터 발췌를한다.
if (part == " ") break; // part 스트링에서 블랭크를 찾으면 멈추고
cout << part << endl; //part 를 출력한다.
result += stoi(part); //stoi 함수로 문자열을 숫자열로변환시켜 result 값에 더해줘서 result 값에 리턴시킨다.
break;
}
}
else { //-문자열 검색에서 -의 인덱스 값이 적을떄
if (Subindex == -1) { //위와 유사
string part = s.substr(startIndex); //
if (part == " ") break;
cout << part << endl;
result -= stoi(part);
break;
}
}
if (Addindex < Subindex) { //+의 인덱스 값이 작을때
int count = Addindex - startIndex; // count에 +인덱스 값에서 선언된start인덱스(최초는 0) 값을 자르고 넣는다.
string part = s.substr(startIndex, count) //part string에 start인덱스부터 count 까지 발췌한다.
;
cout << part << endl; //part 스트링에 발췌한 문자열을 출력한다.
result += stoi(part); //stoi로 part 스트링의 문자열을 숫자로 변환시키고 연산후 대입한다.
startIndex = Addindex + 1; //startIndex 값에서 찾은 Addindex값에서 인덱스 위치를 플러스 1한다
} // 그후 다음 while 반복으로 돌아간다.
else { //-의 인덱스 값이 작을때
int count = Subindex - startIndex; // 위와 논리 유사
string part = s.substr(startIndex, count)
;
cout << part << endl;
result -= stoi(part);
startIndex = Subindex + 1;
}
} // 반복 조건이 더이상 없으므로 종료하고
cout << "계산식의 결과는 : " << result << endl; //합산된 result 결과값을 출력한다.
}이렇게 됐는데... 혹시 접근법이나 다른 아이디어 있으신분 알려주실 수 있나요?
Forums:

http://www.cplusplus.com
http://www.cplusplus.com/reference/string/string/find_first_not_of/
https://www.acmicpc.net/problem/1918 문제를 풀기위해 노력해보세요.
댓글 달기