【问题标题】:Binary String to Integer Stack [duplicate]二进制字符串到整数堆栈[重复]
【发布时间】:2020-11-15 19:22:08
【问题描述】:

努力将字符串分成包含 1 和 0 的堆栈。目前我正在尝试遍历字符串并将它们解析为整数以添加到堆栈中。 我正在输入 1010,其中结果是 1010 , 010, 10, 0 而不是所需的堆栈是 1, 0, 1, 0

我已经使用 atoi 和 stoi 以及索引和 .at 方法来解决我仍然遇到相同问题的地方。


#include <iostream>
#include <string>
#include <stack>

using namespace std;

bool isParsableInt(string input) {
    string nums = "1234567890";
    string test = input;
    int attempt;
    try {
        if (test == "") { return false; }
        if (test[0] == '-') {
            test = test.substr(1, test.length() - 1);
        }
        for (int i = 0; i < test.length(); i++) {
            if (nums.find(test[i]) == string::npos) { return false; }
            attempt = atoi(&test[i]); // String to integer
        }
        return true;
    }
    catch (...) { // Catches any error thrown
        return false;
    }
}



stack<int> createBinaryStack() {
    string input;
    stack<int> result = stack<int>();
    while (true){
        cout << "Enter a binary number : ";
        cin >> input;
        if (!isParsableInt(input)) {
            cout << "Invalid Input found - Must be 1's & 0's" << endl;
            continue;
        }
        if (count(input, '0') + count(input, '1') != input.length()) {
            cout << "Invalid Number found - Must be 1's & 0's" << endl;
            continue;
        }
        for (int i = 0; i < input.length(); i++) {
            cout << stoi(&input.at(i)) << "\t"; // Issue on atoi and stoi functions do not seem to work
            result.push(stoi(&input.at(i)));
        }
        cout << endl;
        return result;
    }
}


int binaryStackToDecimal(stack<int> stk){
    int count = stk.size();
    int total = 0;
    for (int i = 0; i < count; i++) {
        if (stk.top() != 1 && stk.top() != 0) {
            return -1; 
        }
        total += stk.top() * pow(2, i);
        stk.pop();
    }
    return total;
}



int main(){
    stack<int> stk = createBinaryStack();
    while (!stk.empty()) {
        cout << stk.top();
        stk.pop();
    }
    cout << endl;
    cout << binaryStackToDecimal(stk);
}

【问题讨论】:

    标签: c++ stack g++ data-conversion


    【解决方案1】:
    stoi(&input.at(i))
    

    应该是

    input.at(i) - '0'
    

    或者,因为你只处理零和一个更简单的

    input.at(i) == '1'
    

    也有效(与许多其他变体一样)。

    您的错误在于使用旨在将数字序列转换为数字(stoiatoi)的函数,而您只想转换单个数字。 p>

    【讨论】:

    • input.at(i) - '0' 对我不起作用,但我做了比较方面并直接推送 1 和 0 而不是转换。同意第二个陈述,即 stoi 和 atoi 用于一系列数字,我同意这是问题的一个重要部分,不太确定如何处理。
    • @SeanMorgan 我很惊讶,它应该可以工作,当你尝试它时发生了什么?
    • 我只是用它重新运行它并且它出现正确,这很奇怪我可能忘记保存和编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2012-08-16
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多