题目描述(50分): 
通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。
输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。
 
补充说明:
1. 操作数为正整数,不需要考虑计算结果溢出的情况。
2. 若输入算式格式错误,输出结果为“0”。
 
要求实现函数: 
void arithmetic(const char *pInputStr, long lInputLen, char *pOutputStr);
 
【输入】 pInputStr:  输入字符串
         lInputLen:  输入字符串长度         
【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
 
【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出
 
示例 
输入:“4 + 7”  输出:“11”
输入:“4 - 7”  输出:“-3”
输入:“9 ++ 7”  输出:“0” 注:格式错误
 
 
我的程序:
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s;
	string s1,s2,oper;
	getline(cin,s);

	int a=s.find(" ");
	s1=s.substr(0,a);
	s.erase(0,a+1);

    int b=s.find(" ");
	oper=s.substr(0,b);

	s.erase(0,b+1);
	s2=s;
	int c=atoi(s1.c_str());
	int d=atoi(s2.c_str());
	if(oper=="+")
		cout<<c+d<<endl;
	else if(oper=="-")
		cout<<c-d<<endl;
	else
		cout<<0<<endl;

	return 0;
}

  

 

注意 VC6.0中getline()函数需要输入两次回车才能输入,可能是VC6.0的bug,在VS2010中输入一次回车就可以

posted on 2015-05-17 20:45  三人纷纷  阅读(1069)  评论(0编辑  收藏  举报