机试题:过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。

问题描述:通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。
输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。
补充说明: 1. 操作数为正整数,不需要考虑计算结果溢出的情况。 2. 若输入算式格式错误,输出结果为“0”。
示例:
输入:“4 + 7”
输出:“11”
输入:“4 - 7”
输出:“-3”
输入:“9 ++ 7”
输出:“0” 注:格式错误

#include <iostream>
#include "string"
#include <sstream>
using namespace std;
//将string型数字转换成int型,并计算结果
void convert_str_to_int_and_computer(string *scr,string *dst)
{
    int int_temp1 = 0;
    int int_temp2 = 0;
    int res = 0;
    //1 运算的第一位
    string str_temp1 = *scr;
    stringstream ss_temp1;//利用stringstream将int数字转成成string
    //2 运算符
    string operator_flag = *(scr+1);
    //3 运算的第二位
    string str_temp2 = *(scr+2);
    stringstream ss_temp2;
    //4 结果
    stringstream res_temp1;

    //将string型数字转成int型
    int_temp1 = atoi(str_temp1.c_str());
    int_temp2 = atoi(str_temp2.c_str());

    /*/利用原始方法将string型数字转成int型
    for (int i = 0; i < str_temp1.length(); i++)
    {
        int_temp1 = int_temp1 + (int)(str_temp1[i]-'0')*pow(10,str_temp1.length()-i-1);
    }
    for (int j = 0; j < str_temp2.length(); j++)
    {
        int_temp2 = int_temp2 + (int)(str_temp2[j]-'0')*pow(10,str_temp2.length()-j-1);
    }*/

    ss_temp1<<int_temp1;
    ss_temp1>>*(dst);

    *(dst+1) = operator_flag;

    ss_temp2<<int_temp2;
    ss_temp2>>*(dst+2);

    if (operator_flag == "+")
    {
        res = int_temp1 + int_temp2;
    }else if (operator_flag == "-")
    {
        res = int_temp1 - int_temp2;
    }else
    {
        res = 255;
    }
    res_temp1<<res;
    res_temp1>>*(dst+3);
}
void main()
{
    //存储输入数据
    string str;
    //存储去掉空格后的数据
    string str_array[3];
    //存储最终结果
    string res_array[4];

    getline(cin,str);
    int str_array_index = 0;//str_array[]索引
    for (int i = 0; i < str.length(); i++)
    {
        string temp = "";
        int step = 0;
        for (int j = 0; ' '!=str[i+j]&& (i+step)<str.length(); j++)
        {
            temp = temp+str[i+j];
            step++;
        }

        if (""!=temp)
        {
            str_array[str_array_index] = temp;
            str_array_index++;
        }
        i = i +step;//这一步很重要
    }
    //条用函数计算
    convert_str_to_int_and_computer(str_array,res_array);

    //输出结果
    if ("255"!=res_array[3])
    {
        cout<<res_array[0]<<" "<<res_array[1]<<" "<<res_array[2]<<" = "<<res_array[3]<<endl;
    }else
    {
        cout<<"运算符错误,请重新输入!"<<endl;
    }
    cin.get();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值