Background: I just finished an exercise that involved making a stack using linked lists, and then using a vector of char stack to perform various functions such as converting decimal numbers to binary, hexadecimal, and octal, and reversing a string. The final step of the conversion involved pushing each character (e.g. remainder in a number system pushed in the stack) in a string for printing. Check out the Decimal to Octal program below for a better understanding:
Stack <int> stack; //Using a stack of char to store each remainder.
int input; //Store user input.
int remainder; //Store remainder for each step.
string converter("01234567"); //Map the octal number system.
string octal; //Store the final octal number.
do { //Ask the user to input a positive number.
cout << "Please enter a postive number to be converted to its equivalent octal number: ";
cin >> input;
} while (input <= 0);
while (input != 0) { //Creation of the octal numbers and pushing them into the stack.
remainder = input % 8; //Get the remainder of the input after dividing it by 8.
stack.push(converter[remainder]); //Add the remainder in the stack.
input = input / 8; //Get the quotient (whole number) of the input after its division by eight.
//Repeat until the quotient is less than 1 (i.e. '0' in the terms of an integer).
}
while (!stack.empty()) { //Push the contents of the stack into the string octal and clear the stack.
octal.push_back(stack.top()); //Add each octal digit last in first out.
stack.pop(); //Clear the stack.
}
//Print the octal number.
cout << "The octal number is: " << octal;
Problem: I tried imitating the stack using a vector of integers, and tried the above method, but printing the string in the code below does not output anything:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> v;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
string s;
for(int j = 0; j < v.size(); j++) {
s.push_back(v.back());
v.pop_back();
}
cout << s;
return 0;
}
Note:
I did notice that if I try something such as s.pushback('c');
, the char 'c' gets added to the string and could be printed.
Also, the stack program is built on a template implementation of linked list. So I have four files: list.h, list.cpp, stack.h, and stack. cpp. And the main.cpp for experimenting with different functions.