final
By: poleXican | Date: Nov 27 2007 03:34 | Format: C++ | Expires: never | Size: 2.35 KB | Hits: 1155
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <stack>
- #include <cstdlib>
- using namespace std;
- string dectobin(unsigned int num);
- string convert(int num, int n);
- int main()
- {
- ifstream infile;
- ofstream outfile;
- infile.open("input6.txt");
- outfile.open("ouput6.txt");
- string x;
- int decimalnum;
- int bits;
- infile >> bits;
- if (!infile)
- cout<<"Unable to open file input5.txt";
- outfile:
- while(infile >> decimalnum)
- {
- //cout << decimalnum;
- x = convert(decimalnum,bits);
- outfile << decimalnum << " = " << x << endl; //outputs the value of dectobin
- }
- infile.close();
- outfile.close();
- system("PAUSE");
- return 0;
- }
- string convert(int num, int n)
- {
- stack<char> tmpStack,myStack;
- string y;
- string myReturn;
- int num2;
- int tmpInt;
- bool doIt = false;
- if ( num > 0)
- {
- y = dectobin(num);
- //cout << y << endl;
- }else
- if ( num <0)
- {
- num2 = (num*-1);
- y = dectobin(num2);
- }
- while (y.size() <= n-1 )
- {
- y = "0" + y;
- }
- //Check to see if number if GT 0
- if ( num < 0) {
- for (int k=0;k<y.length();k++) {
- tmpStack.push(y[k]);
- }
- while (!tmpStack.empty()) {
- if (tmpStack.top() == '1' && doIt) {
- myStack.push('0');
- }
- else if (tmpStack.top() == '1' && !doIt) {
- myStack.push('1');
- doIt = true;
- }
- else if (tmpStack.top() == '0' && doIt) {
- myStack.push('1');
- }
- else if (tmpStack.top() == '0' && !doIt) {
- myStack.push('0');
- }
- tmpStack.pop();
- }
- while (!myStack.empty()) {
- myReturn += myStack.top();
- myStack.pop();
- }
- return myReturn;
- }
- return y;
- }
- string dectobin(unsigned int num)
- {
- string b;
- if( num > 0)
- {
- b = dectobin(num/2) +
- static_cast<char>('0'+ (num % 2));
- return b; // <--- return the concatenation
- }
- return ""; // <--- return the empty string (in case num == 0)
- }
Latest pastes
17 hours ago
19 hours ago
23 hours ago
2 days ago
2 days ago