Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <string>
- #include <iostream>
- using namespace std;
- void chooseInput(int& inputType)
- {
- bool incorrect;
- string line;
- do
- {
- incorrect = false;
- cout << "Do you want to input from file? (y/n)" << endl;
- cin >> line;
- if (line != "Y" && line != "y" && line != "N" && line != "n")
- {
- incorrect = true;
- cout << "Enter valid answer" << endl;
- }
- } while (incorrect);
- if (line == "N" || line == "n")
- inputType = 1;
- else
- inputType = 0;
- }
- string inputFileLocation()
- {
- bool incorrect = false;
- string location = "";
- cout << "Enter file location:" << endl;
- cin >> location;
- ifstream file(location);
- if (file.is_open())
- {
- cout << "File opened successfully\n";
- return location;
- }
- else
- {
- cout << "File with this location is not found" << endl;
- }
- file.close();
- }
- int getSizeFromFile()
- {
- int size = 0;
- string line;
- ifstream file(inputFileLocation());
- file.clear();
- file.seekg(0, ios::beg);
- file >> size;
- getline(file, line, '\n');
- file.close();
- return size;
- }
- void outputToFile(int** triangle, int size)
- {
- ofstream file(inputFileLocation());
- for (int i = 0; i < size; i++)
- {
- for (int j = 0; j < i; j++)
- {
- file << triangle[i][j] << endl;
- }
- cout << endl;
- }
- }
- void createTriangle(int size, int** triangle) {
- for (int n = 0; n <= size; n++) {
- triangle[n][0] = triangle[n][n] = 1;
- for (int k = 1; k < n; k++) {
- triangle[n][k] = triangle[n - 1][k - 1] + triangle[n - 1][k];
- }
- }
- }
- int getSizeFromConsole()
- {
- const int MAX_VALUE = 30;
- const int MIN_VALUE = 1;
- int size = 0;
- bool isIncorrect;
- do
- {
- cin >> size;
- isIncorrect = false;
- if (size < MIN_VALUE || size > MAX_VALUE)
- {
- isIncorrect = true;
- cout << "Please enter a natural value less than six\n";
- }
- } while (isIncorrect);
- return size;
- }
- void printTriangle(int** triangle, int size)
- {
- for (int i = 0; i < size + 1; i++)
- {
- for (int j = 0; j < i; j++)
- cout << triangle[i][j] << " ";
- cout << endl;
- }
- }
- int main()
- {
- setlocale(LC_ALL, "RUSSIAN");
- cout << "Данная программа строит треугольник Паскаля заданного размера.\n";
- int chosenInput;
- int size = 0;
- chooseInput(chosenInput);
- cout << "Enter the size of Pascal`s triangle\n";
- if (chosenInput == 0)
- {
- size = getSizeFromFile();
- }
- else
- {
- size = getSizeFromConsole();
- }
- cout << endl;
- int** triangle = new int* [size + 1];
- for (int i = 0; i < size + 1; i++)
- triangle[i] = new int [size + 1];
- cout << "Triangle:" << endl;
- createTriangle(size, triangle);
- cout << endl << "Pascal`s triangle" << endl;
- printTriangle(triangle, size);
- outputToFile(triangle, size);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement