C++ 스트링클래스 연산관련 질문입니다.

익명 사용자의 이미지

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 결과값을 출력한다.
}

이렇게 됐는데... 혹시 접근법이나 다른 아이디어 있으신분 알려주실 수 있나요?

bushi의 이미지

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.