Struggling to separate a string into a stack containing 1's and 0's. Currently I am trying to iterate through the string and parse them into integers to add to a stack. I am entering 1010, in which the result is 1010 , 010, 10, 0 instead of the desired stack being 1, 0, 1, 0
I have used atoi and stoi along with indexing and the .at method to where I still have the same issue.
#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);
}
stoi(&input.at(i))
should be
input.at(i) - '0'
or, since you are only dealing with zero and one the even simpler
input.at(i) == '1'
also works (as do many other variations).
Your mistake was taking functions that are intended to convert a sequence of digits to a number (stoi
and atoi
) when all you wanted to do is convert a single digit.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments