Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. string DecToBin(int number)
  8. {
  9.     string result = "";
  10.     do
  11.     {
  12.         if ((number & 1) == 0)
  13.             result += "0";
  14.         else
  15.             result += "1";
  16.         number >>= 1;
  17.     } while (number);
  18.  
  19.     reverse(result.begin(), result.end());
  20.     return result;
  21. }
  22.  
  23. int BinToDec(string number)
  24. {
  25.     int result = 0, pow = 1;
  26.     for (int i = number.length() - 1; i >= 0; --i, pow <<= 1)
  27.         result += (number[i] - '0') * pow;
  28.  
  29.     return result;
  30. }
  31.  
  32. void sort(int tab[], int n)
  33. {
  34.     for (int i = 0; i < n; i++)
  35.     {
  36.         for (int j = 1; j < n - i; j++)
  37.         {
  38.             if (tab[j - 1] > tab[j])
  39.                 swap(tab[j - 1], tab[j]);
  40.         }
  41.     }
  42. }
  43.  
  44.  
  45. int main()
  46. {
  47.     int counter = 0;
  48.     int tab[100];
  49.     string line;
  50.  
  51.     ifstream myfile("file.txt");
  52.     if (myfile.is_open())
  53.     {
  54.         while (getline(myfile, line))
  55.         {
  56.             tab[counter] = BinToDec(line);
  57.             counter++;
  58.         }
  59.  
  60.         myfile.close();
  61.     }
  62.     else
  63.         cout << "Unable to open file";
  64.  
  65.     sort(tab, 100);
  66.  
  67.     for (int i = 0; i < 100; i++)
  68.         cout << i+1 << ". " << "DEC: " << tab[i] << " BIN: " << DecToBin(tab[i]) << endl;
  69.  
  70.     system("PAUSE");
  71.  
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement