When a user enters a city I need the program to search the .txt file if their is already a town with that name. I am using a while( !txtfile.eof() ) to go thru every line in the txt file. As going through every line I have a variable "name" that is getting the value of the line that the while loop has red. And now i somehow need to ignore the " #?city#!= " and start reading from this point until it reaches the " #! ".
using the indexes isn't gonna work for me at this case.
How can I tell the program - Look you smart ass... Start reading after you hit " #?city#!= "combination of characters and read (including spaces) until you get to the " #! ". :)
There are many ways to do that, most of which are generally boiled down to
1) reading the file line by line (e.g. with while(getline(txtfile, line)) -- please don't use "while(!txtfile.eof())"!)
2) examining the line for the character sequence "#?city#!=" followed by the name of the city you're looking for followed by the character sequence "#!"
Here are a couple examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
int main()
{
std::cout << "Enter the city to search for\n";
std::string city;
getline(std::cin, city);
std::regex re("#?city#!=" + city + "#!.*");
std::ifstream f("test.txt");
for(std::string line; getline(f, line); )
if(std::regex_match(line, re))
std::cout << "City found in the file\n";
}
or, if you're limited to old C++,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <fstream>
#include <string>
const std::string prefix = "#?city#!=";
const std::string suffix = "#!";
int main()
{
std::cout << "Enter the city to search for\n";
std::string city;
getline(std::cin, city);
std::ifstream f("test.txt");
for(std::string line; getline(f, line); )
if(line.find(prefix + city + suffix) != std::string::npos)
std::cout << "City found in the file\n";
}
Zagreb - name of the city
70 - distance to Zagreb from my location
I need to compare the input if it is == to a city already in the txt file. Assuming now that the user has inputted Zagreb I need my program to be able to find it and it will change a certain variable to "true" and after that, with a function I will be needing to get the distance which is 70.