Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef _H_READFILE
- #define _H_READFILE
- #include <string>
- #include <fstream> //Read File
- #include <math.h> //pow(x,y)
- #include <vector>
- using namespace std;
- /*
- 0: 48
- 9: 57
- -: 45
- */
- // Converts a string into a number
- int stringtoint(string input, bool &error) {
- int number = 0; //our converted number
- bool sign = false; //positive or negative number
- if((int)input[0] == 10) { //Zeilumbruchzeichen rauslöschen
- string new_input = "";
- for(unsigned int i = 0; i < input.size() - 1; i++) {
- new_input += input[i + 1];
- }
- input = new_input;
- }
- if((int)input[0] == 45) { //Vorzeichen einbeziehen
- number *= -1;
- //Vorzeichen aus dem String löschen
- string new_input = "";
- for(unsigned int i = 0; i < input.size() - 1; i++) {
- new_input += input[i + 1];
- }
- input = new_input;
- }
- for(unsigned int i = 1; i <= input.size(); i++) {
- if(((int)input[i - 1] < 48) || ((int)input[i - 1] > 57)) { //Number not found
- error = true;
- break; //leave for-loop because wrong character found
- } else {
- number += ((int)input[i - 1] - 48) * pow(10, input.size() - i);
- }
- }
- if(sign) {
- number *= -1;
- }
- return number;
- }
- //Liest Datei ein, schreibt den Inhalt in die Matrizen rein und gibt zurück ob alles geklappt hat oder nicht
- bool ReadFile(string filename, vector<vector<int> > &mat_pref, vector<vector<int> > &mat_cost) {
- ifstream file;
- string line;
- bool error = false; //readerror
- unsigned int nodes = 0;
- file.open(filename.c_str(), ios::in);
- if(file.good()) {
- getline(file, line);
- nodes = stringtoint(line, error);
- if(error) {
- cout << "Unknown number found in input file: " << line << endl;
- cout << "Aborting prograrm" << endl;
- return false;
- }
- cout << nodes << endl;
- vector<int> temp(nodes, 0);
- for(unsigned int i = 0; i < nodes; i++) {
- //"nodes" Zahlen die mit Leerzeichen separiert sind einlesen
- for(unsigned int j = 0; j < nodes; j++) {
- getline(file, line, ' ');
- temp[j] = stringtoint(line, error);
- if(error) {
- cout << "Unknown number found in input file: " << line << endl;
- cout << "Aborting prograrm" << endl;
- return false;
- }
- }
- mat_pref.push_back(temp); //"Array"(Zeile) in die "Matrix" einfügen
- }
- //"nodes" Zeilen einlesen
- for(unsigned int i = 0; i < nodes; i++) {
- //"nodes" Zahlen die mit Leerzeichen separiert sind einlesen
- for(unsigned int j = 0; j < nodes; j++) {
- getline(file, line, ' ');
- temp[j] = stringtoint(line, error);
- if(error) {
- cout << "Unknown number found in input file: " << line << endl;
- cout << "Aborting prograrm" << endl;
- return false;
- }
- }
- mat_cost.push_back(temp); //"Array"(Zeile) in die "Matrix" einfügen
- }
- file.close();
- return true; //Alles hat geklappt
- } else { //Datei konnte nicht zum Lesen geöffnet werden
- cout << "File not found or broken!" << endl;
- file.close();
- return false;
- }
- }
- #endif
Add Comment
Please, Sign In to add comment