- #include<iostream>
- #include<cstdlib>
- #include<sstream>
- #include<string>
- using namespace std;
- int main()
- {
- string str;
- cout<<"請輸入一個加法算式 (譬如 5+7+2): ";
- cin>>str;
- str+="+";
-
- string tmp="";
- int sum=0;
- stringstream ss;
- int n;
- for(int i=0;i<str.size();i++)
- {
- if(str[i]=='+')
- {
- ss<<tmp;
- ss>>n;
- sum=sum+n;
-
- tmp="";
- ss.clear();
- }
- else{
- tmp+=str[i];
- }
- }
-
- cout<<str.substr(0,str.length()-1)<<"="<<sum<<endl;
-
- system("pause");
- return 0;
- }
複製代碼 |