簡體   English   中英

加號轉義C ++

[英]plus sign escape c++

嗨,大家好,我在獲取輸入時遇到加號困難。 在這里,我正在處理反向拋光符號計算器。 我要輸入的是“ 3 2 + $”,這意味着(以簡單的方式)將3和2相加並顯示出來。 我試圖使用stringstreams while(cin)。 現在我試圖一一獲得輸入;

int num;
char ch;
while (cin)
    {
        if (cin >> num)
        {
            cout<<num;
        }
        else
        {
            cin.clear();
            cin >> ch;
            cout << ch;
        }
    }
}

它不適用於+和-,適用於*和/。 但是我也需要那些操作數。 我通過getline嘗試了istringstream。 它沒有看到+或-。

在示例代碼中,這一行讓我擔心while (cin) (一定要無限循環),而在示例代碼中則是這樣(我補充說,當輸入空白行時,程序將結束)。

當您在控制台中輸入cin >> somevariable;時,cin將在輸入中一個單詞接一個單詞3 2 + $ cin >> somevariable; 會得到4個結果: 3個然后2個然后+ ,最后$個 讀取波蘭語符號時的另一個問題是,您無法預測下一個標記是數字還是運算符,則可能得到: 3 2 + $3 2 2 + * $也是如此。 因此,您需要一個容器來存儲操作數。

這是一個小例子:

#include <iostream>
#include <stack>
#include <boost/lexical_cast.hpp>

using namespace std;

int main(int argc, char *argv[]) {
    string read;
    std::stack<int> nums;
    while (cin >> read) {
        if (read.empty()) {
            break;
        }
        else if (read == "$") {
            std::cout << nums.top() << std::endl;
        }
        else if (read == "+" || read == "-" || read == "*" || read == "/") {
            if (nums.size() < 2) {
            } // error code here

            int n1 = nums.top();
            nums.pop();
            int n2 = nums.top();
            nums.pop();

            if (read == "+")
                nums.push(n2 + n1);
            if (read == "-")
                nums.push(n2 - n1);
            if (read == "*")
                nums.push(n2 * n1);
            if (read == "/")
                nums.push(n2 / n1);
        }
        else {
            try {
                nums.push(boost::lexical_cast<int>(
                    read)); // you should add convertion excepcion code
            }
            catch (...) {

            }
        }
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM