Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <fstream>
- using namespace std;
- void showMatrix(vector<vector<string>> &matrix) {
- for(int i = 0; i < matrix.size(); i++) {
- for(int j = 0; j < matrix[i].size(); j++) {
- cout << matrix[i][j] << " ";
- }
- cout << endl;
- }
- }
- vector<string> split(string str, string delimiter) {
- vector<string> result;
- int pos = 0;
- while(pos != -1) {
- pos = str.find(delimiter);
- result.push_back(str.substr(0, pos));
- str.erase(0, pos + delimiter.length());
- }
- return result;
- }
- vector<vector<string>> getMatrixFromFile(ifstream& inputFile) {
- vector<vector<string>> matrix;
- vector<string> row;
- string line = "";
- while (getline(inputFile, line)) {
- row = split(line, " ");
- matrix.push_back(row);
- }
- return matrix;
- }
- int checkMatrix(vector<vector<string>> &matrix) {
- int raw = -1;
- int lastMaxZeroesCount = 0;
- for(int i = 0; i < matrix.size(); i++) {
- int zeroes = 0;
- for(int j = 0; j < matrix[i].size(); j++) {
- if(stoi(matrix[i][j]) == 0)
- zeroes++;
- }
- if(zeroes > lastMaxZeroesCount) {
- lastMaxZeroesCount = zeroes;
- raw = i;
- }
- }
- return raw;
- }
- int main() {
- cout << "Данная программа находит строку матрицы, в которой больше всего нулевых элементов\n" << endl;
- cout << "Введите путь к файлу" << endl;
- bool noException = true;
- string filePath;
- cin >> filePath;
- ifstream inputFile;
- inputFile.open(filePath);
- vector<vector<string>> matrix;
- if(inputFile) {
- matrix = getMatrixFromFile(inputFile);
- inputFile.close();
- } else {
- cout << "Произошла ошибка при чтении файла. Убедитесь, что такой файл существует, либо проверьте имя файла." << endl;
- noException = false;
- }
- if(noException) {
- cout << "Получившаяся матрица:\n";
- showMatrix(matrix);
- int result = checkMatrix(matrix)+1;
- string resultText = "";
- if (result == 0)
- resultText = "Нули отсутствуют";
- else
- resultText = "Строка, в которой больше всего нулевых элементов - " + to_string(result);
- cout << resultText << endl;
- ofstream outputFile;
- outputFile.open("output.txt");
- outputFile << resultText;
- cout << "Результат сохранен в файл output.txt" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement