C++ 简单程序 - 为什么我的 "res"没有进入我的 vector ?创建一个接受输入 (4+44-67+235) 并输出结果的程序

标签 c++

<分区>

我修复了 -'0' 错误,现在我的输出与我的输入有些相关。我相信这是将我的第一个“c”值乘以 10,而不是其他值。我如何获得像 143 这样的数字的正确值以计算到我的输出中?

#include <vector>
#include <string>
#include <iostream>

using namespace std;
class token { 
    public: char kind;
            char value;
};

int main(){
    vector<token> vt;
    char c;
    token t;
    int res = 0;
    while (cin>>c){
        if(c!= '+' && c!= '-' && c!= '='){

            res = res*10+c-'0';
        }
        else {
            t.kind = c;
            t.value = res;

            vt.push_back(t);
            res = 0;

        }
        if (c=='=')
            break;
    }
    int num = vt[0].value-'0';
    for(int i=0; i<vt.size(); i++){
        if (vt[i].kind=='+')
            num+=vt[i+1].value-'0';
        if (vt[i].kind=='-')
            num-=vt[i+1].value-'0';
    }
    cout<<num;
    system("pause");
}

最佳答案

读取输入时减去“0”就足够了,您不必在遍历元素时再次减去它。

关于C++ 简单程序 - 为什么我的 "res"没有进入我的 vector ?创建一个接受输入 (4+44-67+235) 并输出结果的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113202/

相关文章:

c++ - Char 数组正确输出但实际上未存储正确的值

c++ - 将 sigwait 与 std::thread 和管道一起使用

c++ - 运行来自 Learning Opencv 的练习 2-4 的问题,O'Reilly

C++ 对象转字符串

c++ - 为什么在 Boost 中有两个变体类实现?

c++ - 在新进程中运行方法并等待它们完成

c++ - 使用按位运算符的 PE 文件格式指针

c++ - HTTP multipart/form-data 发送一个字符串数组

c++ - g++ - 无优化 - 在转到后跳过 asm 代码

c++ - 仅包含<opencv2/opencv.hpp>会导致链接错误