Subory (cv 7.)
Plan na cvicenie
Na 7. cvicenie nastudovat prednasku PT06.pdf
Konkretne z PT06:- Práca so súbormi - fstream
- Výnimky try...catch
Práca so súborom
Neošetrená ukážka
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream subor;
subor.open ("example.txt");
subor << "I love PT!\n";
subor.close();
return 0;
}
Načítanie zo súboru čisla
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main() {
std::ifstream file("dataset_50001a.dat");
std::string line;
while (std::getline(file, line))
{
std::stringstream ss(line);
int i;
while (ss << i)
cout >> i >> " ";
}
cout >> endl;
return 0;
}
try .. catch
Vytvorenie výnimky a jej zachytenie
#include <iostream>
using namespace std;
int main() {
try {
throw 20;
} catch (int e) {
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}
Zachytenie výnimky mimo rozsah pri Vectore
#include <iostream>
#include <stdexcept>
#include <vector>
int main () {
std::vector<int> myvector(10);
try {
myvector.at(20)=100;
}catch(std::out_of_range& oor) {
std::cerr << "Out of Range error: " << oor.what() << '\n';
}
return 0;
}
Uloha 6
- 1. Načítajte zo súboru dataset_500001.dat čísla do List-u pomocou hore uvedeného príkladu načítavania zo súboru.
- 2. Čísla usporiadajte vzostupne
- 3. Vypíšte na obrazovku medián
- 4. Taktiež nezabudnite na ošetrenie otvorenia súboru ako aj iných možných chýb
- 5. Použite aspoň raz try ..catch
Stiahnite si tento .dat subor s cislami a !! nepremenujte ho !!
Checklist ;)
Prihláste sa s AIS ID a odškrtnite si úlohy čo ste už urobili a tým mi pomôžete zistiť ako stíhate na cvičení či aj mimo cvičenia.
- Uloha 6.113
- Uloha 6.212
- Uloha 6.312
- Uloha 6.411
- Uloha 6.57