Содержание
ВНИМАНИЕ | Для заказа программы пишите на наш электронный адрес proglabs@mail.ru |
Условие задачи
Считать из файла данные (фамилия и средний балл) и сохранить их в некоторую структуру данных.
По запросу пользователя вывести наибольшее или наименьшее значение среднего балла.
Входные данные
Реализация задачи на языке C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | #include <iostream> // для консольного ввода-вывода #include <string> // для работы со строками #include <iomanip> // для форматированного ввода-вывода #include <fstream> // для работы с файловыми потоками // подключаем стандартное пространство имен using namespace std; // описываем сущность "Человек" struct Person { string surname; double ball; }; // проверка входного файла с данными bool Is_correct_input_file( const string name_file ) { ifstream input_file( name_file ); if( ! input_file.is_open() ) return false; input_file.close(); return true; } // определяем количество записей во входном файле int Get_records_in_file( const string name_file ) { int count = 0; ifstream input_file( name_file ); string s; while( ! input_file.eof() ) { getline( input_file, s ); count++; } input_file.close(); return count; } // считывание данных из текстового файла в динамический массив структур Person* Get_data_from_file( const string name_file, const int records_count ) { Person* persons = new Person[ records_count ]; ifstream input_file( name_file ); string s; int position = -1; for( int i = 0; i < records_count; i++ ) { position++; // считываем фамилию input_file >> persons[ position ].surname; // пропускаем имя отчество input_file >> s; input_file >> s; // считываем средний балл input_file >> persons[ position ].ball; // считываем конец строки getline( input_file, s ); } input_file.close(); return persons; } // вывод информации на экран void Print( const Person* const persons, const int n ) { cout << endl << endl << "Входная информация имеет вид: " << endl; cout << "-------------------------------------------------" << endl; cout << " № Фамилия Средний балл " << endl; cout << "-------------------------------------------------" << endl; for( int i = 0; i < n; i++ ) { cout << setw( 4 ) << i + 1; cout << setw( 24 ) << persons[ i ].surname; cout << setw( 17 ) << setprecision( 4 ) << fixed << persons[ i ].ball << endl; } cout << "-------------------------------------------------" << endl; } // получение индекса записи с минимальным средним баллом int Get_index_min_ball( const Person* const persons, const int n ) { int index = 0; for( int i = 1; i < n; i++ ) if( persons[ i ].ball < persons[ index ].ball ) index = i; return index; } // получение индекса записи с максимальным средним баллом int Get_index_max_ball( const Person* const persons, const int n ) { int index = 0; for( int i = 1; i < n; i++ ) if( persons[ i ].ball > persons[ index ].ball ) index = i; return index; } // главное меню программы int Menu( void ) { int select; do { system( "CLS" ); cout << "\t\tГЛАВНОЕ МЕНЮ ПРОГРАММЫ" << endl << endl; cout << "\t1 - Считывание данных из текстового файла" << endl; cout << "\t2 - Вывести данные на экран" << endl; cout << "\t3 - Вывести наименьшее значение среднего балла" << endl; cout << "\t4 - Вывести наибольшее значение среднего балла" << endl; cout << "\t5 - Выход" << endl; cout << "\t\tВЫБОР: "; cin >> select; } while( ( select < 1 ) || ( select > 5 ) ); return select; } // главная функция программы (точка входа) int main( void ) { setlocale( LC_ALL, "" ); int select; // хранилище входных данных Person* persons = nullptr; // количество записей в хранилище int persons_count; do { select = Menu(); switch( select ) { case 1: { string name_file; cout << endl << endl << "Введите имя текстового файла с данными: "; fflush( stdin ); getline( cin, name_file ); if( ! Is_correct_input_file( name_file ) ) cout << "Ошибка открытия входного текстового файла с данными!" << endl; else { persons_count = Get_records_in_file( name_file ); // при повторном считывании данных удаляем текущие данные delete[] persons; persons = Get_data_from_file( name_file, persons_count ); cout << "Данные успешно считаны из входного текстового файла." << endl; } break; } case 2: { if( persons == nullptr ) cout << endl << "В базе данных нет данных. Сначала считайте данные из текстового файла."; else Print( persons, persons_count ); break; } case 3: { if( persons == nullptr ) cout << endl << "В базе данных нет данных. Сначала считайте данные из текстового файла."; else { Print( persons, persons_count ); int min_index = Get_index_min_ball( persons, persons_count ); cout << endl << "Студент по фамилии \'" << persons[ min_index ].surname << "\' имеет наименьший балл: " << setprecision( 4 ) << fixed << persons[ min_index ].ball; } break; } case 4: { if( persons == nullptr ) cout << endl << "В базе данных нет данных. Сначала считайте данные из текстового файла."; else { Print( persons, persons_count ); int max_index = Get_index_max_ball( persons, persons_count ); cout << endl << "Студент по фамилии \'" << persons[ max_index ].surname << "\' имеет наибольший балл: " << setprecision( 4 ) << fixed << persons[ max_index ].ball; } break; } } if( select != 5 ) { cout << endl << endl; system( "pause" ); } } while( select != 5 ); // перед выходом из программы удаляем динамическую память delete[] persons; return EXIT_SUCCESS; } |
Результаты работы программы
ВНИМАНИЕ | Для заказа программы пишите на наш электронный адрес proglabs@mail.ru |
Добавить комментарий