Search code examples
c++stringfstreamifstream

Formatting and finding text C++


I'm designing a program code that when given a few select Airport codes it determines the sunrise and sunset times of the week in that given area.

I'd like to point out that because it is for a Advanced C++ Class, I don't want to be handed code. I'd to be shown how to do it, not have someone do it for me.

I have a file in this case cityinfo.txt that contains this information:

APN
 45.07   83.57   E
ATL
 33.65   84.42   E
DCA
 38.85   77.03   E
DEN
 39.75  104.87   M
DFW
 32.90   97.03   C
DTW
 42.23   83.33   E
GRR
 42.88   85.52   E
JFK
 40.65   73.78   E
LAF
 40.42   86.93   E
LAN
 42.77   84.60   E
LAX
 33.93  118.40   P
MBS
 43.53   84.08   E
MIA
 25.82   80.28   E
MQT
 46.53   87.55   E
ORD
 41.98   87.90   C
SSM
 46.47   84.37   E
TVC
 44.73   85.58   E
YYZ
 43.67   79.63   E

The output is like running it does not have the brakes after each time zone code (e,z,c, etc.)

So i have two questions about this:

  • Do I need to format the code when i put it in my string variable, it doesn't need to be outputted just referenced?
  • How can i format it if needed?

Seem to have found the answer for me using the help of you guys are from the public sources of the c++ find function:

    ifstream fileIn;
    string airportCode, lat, longitude, timeZone, line;
    size_t pos;

    cout << "Please Enter an Airport Code: ";
    cin >> airportCode;

    fileIn.open("cityinfo.txt");
    if (fileIn.is_open())
    {
        while (fileIn.good())
        {
            getline(fileIn, line);
            pos = line.find(airportCode);
            if (pos != string::npos)
            {

                fileIn >> lat >> longitude >> timeZone;
                break;
            }

        }

    }

Solution

  • That's a pretty cleanly formatted file.

    You should do fine with something like:

    #include <fstream>
    
    ifstream my_ifstream("data_file.txt");  // Create fstream from file.
    
    while ( my_ifstream )
    {
        std::string airport;
        double rise;
        double set;
        std::string tz;
    
        my_ifstream >> airport >> rise >> set >> tz;
        // Store this data somewhere...
    }
    

    Have you tried anything like that yet?