Advertisement
xTheEc0

Random generated number from user input range.

Oct 16th, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. // Numbers are random generated from user inputted range.
  2. // Results are both written to file and shown in console.
  3. // Result file can be changed @ line 17
  4. // By changing "xx.txt"
  5.  
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <iomanip> // setprecision library
  9. #include <stdio.h> // printf library
  10. #include <string>
  11. #include <cmath>   // mathematical commands // pow() sqrt() abs() ..
  12. #include <limits>  // cin.ignore(numeric_limits<streamsize>::max(),'\n');
  13. #include <fstream> // File input and output.
  14. #include <ctime>   // Time for random generator
  15. using namespace std;
  16.  
  17. const char rezF[] = "3U.txt";
  18.  
  19. // used to find number of digits in a number (1000 = 4) to be used in setw()
  20. template <class T>
  21. int numDigits(T number)
  22. {
  23.     int digits = 0;
  24.     if (number < 0) digits = 1; // remove this line if '-' counts as a digit
  25.     while (number) {
  26.         number /= 10;
  27.         digits++;
  28.     }
  29.     return digits;
  30. }
  31.  
  32. int main(int argc, char *argv[])
  33. {
  34.     // Range: [x;y]
  35.     // a = (x + rand() % (y - x +1)) // Random numbers in range;
  36.  
  37.     // Variables
  38.     int a;
  39.     int x, y;
  40.     int temp;
  41.     int inputedRange;
  42.     ofstream rf(rezF);
  43.  
  44.     cout << "Range in which random numbers will be generated? [x;y]" << endl;
  45.     cout << "From: ";cin >> x;
  46.     cout << "To:   ";cin >> y;
  47.     cout << "" << endl;
  48.     rf << "User selected range" << endl;
  49.     rf << "From: " << x << endl;
  50.     rf << "To:   " << y << endl << endl;
  51.     inputedRange = numDigits(y);    // setting setw() range
  52.     srand(time(NULL));              // Initializing random number @ time
  53.  
  54.     for (int i = 0; i < 10; i++)    // Rows
  55.     {
  56.         for (int j = 0; j < 10; j++)// Lines
  57.         {
  58.             a = (x + rand() % (y - x + 1));
  59.             cout << setw(inputedRange) << a << " ";
  60.             rf << setw(inputedRange) << a << " ";
  61.         }
  62.         cout << "" << endl;
  63.         rf << "" << endl;
  64.     }
  65.     cout << "\nThe numbers have been put in a file.";
  66.  
  67.     // Ending
  68.     cout << " " << endl;
  69.     //system ("PAUSE");
  70.     return EXIT_SUCCESS;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement