Public paste
dddd
By: dddd | Date: Nov 27 2007 01:51 | Format: C++ | Expires: never | Size: 1.69 KB | Hits: 1175

  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <stack>
  5.  
  6.  
  7.  
  8.  
  9. using namespace std;  
  10. string dectobin(unsigned int num);
  11. string convert(int num, int n);
  12.  
  13. int main()
  14.     {
  15.     ifstream infile;
  16.     ofstream outfile;
  17.    
  18.     infile.open("input6.txt");
  19.     outfile.open("ouput6.txt");
  20.    
  21.     string x;
  22.     int decimalnum;
  23.     int bits;
  24.     infile >> bits;
  25.    
  26.     if (!infile)
  27.     cout<<"Unable to open file input5.txt";  
  28.    
  29.     while(!infile.eof())
  30.     {
  31.     infile >> decimalnum;                                
  32.     //cout <<  decimalnum;
  33.     x = convert(decimalnum,bits);
  34.     outfile <<  decimalnum << " = " << x << endl; //outputs the value of dectobin
  35.     }              
  36.  
  37.  
  38.  
  39.      
  40.       infile.close();
  41.       outfile.close();
  42.      
  43.      
  44.      
  45.     system("PAUSE");
  46.     return 0;
  47. }  
  48.  
  49.  
  50. string convert(int num, int n)
  51. {      
  52.  
  53.        string y;
  54.        int num2;
  55.                 stack<char> s;
  56.                
  57.    
  58.           if ( num > 0)
  59.           {
  60.           y = dectobin(num);
  61.           cout << y << endl;
  62.           }else
  63.          
  64.           if ( num <0)
  65.           {
  66.          num2 = (num*-1);
  67.            y = dectobin(num2);
  68.            reverse(y);
  69.            
  70.  
  71.            }
  72.  
  73.  
  74.           while (y.size() <= n-1 )
  75.        {
  76.             y = "0" + y;
  77.            
  78.        }
  79.           return y;    
  80.          
  81. }
  82. string dectobin(unsigned int num)
  83.  
  84. {    
  85.      
  86.         string b;  
  87.         if( num > 0)
  88.         {
  89.         b = dectobin(num/2) +
  90.         static_cast<char>('0'+ (num % 2));
  91.         return b;  // <--- return the concatenation
  92.         }    
  93.         return ""; // <--- return the empty string (in case num == 0)
  94. }