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
|
#include<iostream>
#include<fstream>
#include<string>
int findNthOccur(std::string str, char ch, int N);
void ticket(std::string filename, int km);
int main(){
int km = 0;
std::cout << "Counting price of train trip. Give me a distance in km and I'll return the price of its ticket.\n\n";
do{
std::cout << "Distance (km): ";
std::cin >> km;
ticket("prices.txt", km);
if(km < 0){
break;
}
}while(km > 0);
if(km < 0){
std::cout << "Quitting.";
}
return 0;
}
void ticket(std::string filename, int km){
// int start, end, price;
std::string str, s, e, p;
std::ifstream file(filename);
if(file.is_open()){
std::getline(file, str);
while(!file.eof()){
std::getline(file, str);
std::cout << str << '\n';
if(str != ""){
s = str.substr(0, findNthOccur(str, '\t', 1));
e = str.substr(findNthOccur(str, '\t', 1)+1, findNthOccur(str, '\t', 2)-findNthOccur(str, '\t', 1)-1);
p = str.substr(findNthOccur(str, '\t', 2)+1, findNthOccur(str, '\n', 1)-findNthOccur(str, '\t', 2)-1);
std::cout << "s is: " << s << ", e is: " << e << ", p is: " << p << '\n';
if(std::to_string(km) >= s && std::to_string(km) <= e){
std::cout << "Price of ticket: " << p << '\n';
}
}
}
}
}
int findNthOccur(std::string str, char ch, int N){
int occur = 0;
for (unsigned int i = 0; i < str.length(); i++) {
if (str[i] == ch) {
occur += 1;
}
if (occur == N)
return i;
}
return -1;
}
|