Public paste
code1
By: poleXican | Date: Nov 27 2007 02:49 | Format: C++ | Expires: never | Size: 1.71 KB | Hits: 1219

  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 >> decimalnum)
  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.  
  56.          
  57.      
  58.           if ( num > 0)
  59.           {
  60.           y = dectobin(num);
  61.           }else
  62.            
  63.           if ( num <0)
  64.           {
  65.          num2 = (num*-1);
  66.            y = dectobin(num2);
  67.  
  68.            
  69.  
  70.            }
  71.  
  72.  
  73.           while (y.size() <= n-1 )
  74.        {
  75.             y = "0" + y;
  76.              
  77.        }  
  78.           return y;    
  79.            
  80. }
  81. string dectobin(unsigned int num)  
  82.  
  83. {    
  84.      
  85.         string b;  
  86.         if( num > 0)  
  87.         {
  88.         b = dectobin(num/2) +  
  89.         static_cast<char>('0'+ (num % 2));  
  90.         return b;  // <--- return the concatenation
  91.         }      
  92.         return ""; // <--- return the empty string (in case num == 0)
  93. }