Пример решения задачи на C++
Задача
Описать структуру TRAIN с полями:
- название пункта направления;
- номер поезда;
- время отправления.
Написать программу, выполняющую следующие действия:
- ввод с клавиатуры данных в массив, состоящий из элементов типа TRAIN;
- затем разместить их в алфавитном порядке по названиям пунктов назначения;
- вывод информации о поездах, отходящих после введенного времени;
- если таких поездов нет, выдать на дисплей соответствующее сообщение.
Решение #include <vector> #include <algorithm> #include <functional> #include <iostream>
using namespace std;
struct train { string caption; int number; double times; };
bool operator<(const train &x, const train &y) { if (x.caption.compare(y.caption)<0) return true; else return false; }
ostream& operator<<(ostream &s, const train &x) { cout.width(25); return s << x.caption.data() << "\t" << x.number << "\t" << x.times << endl; }
void ClearBuff() { cin.clear(); cin.seekg(cin.gcount()+1); cin.clear(); }
int main () { int n = 0; double traintime = 0; vector<train>::iterator j, k;
cout << "Please enter quantity of trains:" << endl; cin >> n; ClearBuff(); while (n < 1 || n > 1000) { cout << "Error in input. Please try again." << endl; cout << "Please enter quantity of trains:" << endl; cin >> n; ClearBuff(); }
vector<train> v(n);
cout << "Enter train's: name, number, time" << endl;
for (int i = 0; i < n; i++) { cout << "Enter train N " << i+1 << endl; char ct[25]; int nt = 0; double tt = -1; cin.get(ct, 25); ClearBuff(); cin >> nt; cin >> tt; if (cin && tt>0 && tt<24) { v[i].caption.append(ct, 25); v[i].number = nt; v[i].times = tt; ClearBuff(); } else { ClearBuff(); cout << "Error in input. Please try again." << endl; i--; } }
cout << "Enter train's time" << endl;
cin >> traintime; ClearBuff(); while (traintime < 0 || traintime > 24) { cout << "Error in input. Please try again." << endl; cin >> traintime; ClearBuff(); }
sort(v.begin(), v.end());
cout << "List of train's:" << endl;
bool none = true;
for (int i = 0; i<n; i++) { if (traintime < v[i].times) { cout << v[i]; none = false; } } if (none) cout << "No train's" << endl; system("pause"); return 0; }
:: Рекомендуемая литература.
Посетите интернет-магазины:
Озон,
Болеро
VIP Казань — Казань для достойных людей
|