Member Avatar for kingrev

Hi everyone I hope you guys could give me a hand with this project, I am not an expert of c++ and i am really struggling with this.

here is the problem:

I been asked to make a programn as follows: A new railway journey planner is required to help users determine which of multiple published routes can be completed in a time period specified by the user.

I been also given a txt document with the data that is as follows + format:

Journey One
1 //number of changes (meaning that there would be two trains)
200 90 // first number is the distance and the second is the speed (Distance/speed = time)
100 60

Journey Two
0
300 120

Journey Three
2
50 50
50 75
100 60

the application has to calculate the total journey time for each journey and then compare it with the time period specified by the user. If the journey can be completed in the specified time then the result must be written to the screen and to an output text file called results.txt. If the journey cannot be completed in time then the results must be written to the screen only. Messages to the screen must indicate whether the journey is suitable or not.

*So first the user has to be able to input the time period in minutes or hours (thats one problem)

*then my biggest problem right now is making the data to be read properly, i should be using loops for this but i dont know how to do it... then it has to do the calculation to get the total time for each journey and then compare it to the others + user's
if you guys could help me with anything i would be much apreciated.

here is my code so far but its a propper fail....

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <tchar.h>
#include <string>
#include <cmath>
#include <iomanip>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string JourneyName;
    int TimeRequested;
    int NumberOfChanges;
    int DistanceLenght;
    int DistanceSpeed;
    int TimeRequiered;

    ifstream inFile;
    inFile.open ("JourneyData.txt", ios::in); 

    cout << "Please enter an approximate time you wish your journet to take: ";
    cin >> TimeRequested;


    inFile >> JourneyName;

    getline(inFile, JourneyName);

    inFile >> NumberOfChanges >> DistanceLenght;

    inFile.ignore (1,' ');

    inFile >> DistanceSpeed;
    TimeRequiered = (DistanceLenght / DistanceSpeed); 

    inFile.close();

    system ("pause");
    return 0;
}

Something like this comes to mind as a first attempt:

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>

int main()
{
    std::ifstream in("test.txt");

    if (in) {
        std::string header;

        while (getline(in, header)) {
            if (header.empty())
                continue; // Discard empty lines

            int changes = -1;

            if (!(in>> changes)) {
                std::cerr<<"Invalid file format\n";
                return EXIT_FAILURE;
            }

            for (int i = 0; i <= changes; ++i) {
                int distance, speed;

                if (!(in>> distance >> speed)) {
                    std::cerr<<"Invalid file format\n";
                    return EXIT_FAILURE;
                }

                std::cout<< header <<": ("<< distance <<','<< speed <<")\n";
            }

            std::cout<<'\n';
        }
    }
}
Member Avatar for kingrev

thank you a lot for your time, i am ging start working on it and see if i get somewhere with it, let you know when i get it working or find another problem.

Member Avatar for kingrev

Hey i Have manage to make it work, but i am having a slight problem right now... i dont know where to put the code for the calculation to happen as i need to get the time by doing this:

Time = distance / speed.

This an update on how the code looks right now

i have tried to add the calculation in different parts of the code and i always get the same.... i just get the number of the speed
but btw you have helped me a lot so far thank you so much

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <tchar.h>
#include <string>
#include <cmath>
#include <iomanip>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string JourneyName;
    int TimeRequested;
    int DistanceLenght;
    int DistanceSpeed;
    int TimeRequiered;


    ifstream inFile;
    inFile.open ("JourneyData.txt", ios::in); 

      if (inFile) {

        while (getline(inFile, JourneyName)) {
            if (JourneyName.empty())
                continue; // Discard empty lines

            int NumberOfChanges = -1;

            if (!(inFile>> NumberOfChanges)) {
                cerr<<"Invalid file format\n";
                return EXIT_FAILURE;

            }

    for (int i = 0; i <= NumberOfChanges; ++i) {

        if (!(inFile>> DistanceLenght >> DistanceSpeed)) {
                  cerr<<"Invalid file format\n";
                    return EXIT_FAILURE;

                }
                   TimeRequiered = (DistanceLenght/DistanceSpeed * 60);
        cout<< JourneyName <<": ("<< DistanceLenght <<','<< DistanceSpeed <<")\n";

              }
                cout << "Total Travel Time : " << TimeRequiered << endl;
                cout<<'\n';


           }
      }


    inFile.close();


    system ("pause");
    return 0;
}
Member Avatar for kingrev

update: i manage to find out what is the problem, it only does the calculation for the last values, so lets say if i ask it to print the "speed" or "distance" it would only print me the last values, so when it comes to do the calculation i need the programn to do add all the distance and speed valvues and then divide them been trying number of different ways to do this but failed

You never calculated total time. The variable TimeRequiered simply calculates the time for each change and when you print the value outside the loop it prints the last value.

To calculate total time first initialize the variable TimeRequiered to 0 at the beginning. Then change line# 44 to

TimeRequiered = TimeRequiered + (DistanceLenght/DistanceSpeed * 60);

This will get you the total time for each journey.

BTW, your variables need to be floats or doubles to handle decimals.

Member Avatar for kingrev

You were absolutly right, but now there is another problem... once it has calculated each set, it just adds all of them together so the results of the previous one is added to next one how can i stop this ?

Thank you btw

Judicious use of variable scoping can take care of that. Note how in the following code I've moved variable definitions to the smallest scope possible. I also initialized time to 0, adjusted your variable names to be more consistent/conventional, removed unnecessaries and tightened things up a bit:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    ifstream inFile("test.txt"); 

    if (inFile) {
        string journeyName;

        while (getline(inFile, journeyName)) {
            if (journeyName.empty())
                continue; // Discard empty lines

            int nChanges = -1;

            if (!(inFile>> nChanges)) {
                cerr<<"Invalid file format\n";
                return EXIT_FAILURE;
            }

            double time = 0; // Get your ass in gear soldier!

            for (int i = 0; i <= nChanges; ++i) {
                double length, speed;

                if (!(inFile>> length >> speed)) {
                    cerr<<"Invalid file format\n";
                    return EXIT_FAILURE;
                }

                time += (length / speed * 60);
            }

            cout<<"Travel time for "<< journeyName <<": "<< time <<'\n'<<endl;
        }
    }
}
Member Avatar for kingrev

Thanks a lot it totally worked, damn i must say though no one would of helped me, learned a lot from this post hopefully one day i'll get as good as you guys

Member Avatar for kingrev

The program is almost done but i one but last question...
the last bit of the programn has to compare the times of each Journey and then compare them to the time the user has entered and then output the quickest journey.
i been doing the IF statements and once it meets the requirements outputs all of them, well the ones that meets the requirement, any ideas ?

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
   double TimeRequested;

    ifstream inFile("test.txt"); 

    cout << " Please enter approximate time you wish your journey to take : ";
    cin >> TimeRequested;

    if (inFile) {
        string journeyName;
        while (getline(inFile, journeyName)) {
            if (journeyName.empty())
                continue; // Discard empty lines
            int nChanges = -1;
            if (!(inFile>> nChanges)) {
                cerr<<"Invalid file format\n";
                return EXIT_FAILURE;
            }
            double time = 0; 
            for (int i = 0; i <= nChanges; ++i) {
                double length, speed;
                if (!(inFile>> length >> speed)) {
                    cerr<<"Invalid file format\n";
                    return EXIT_FAILURE;
                }
                time += (length / speed * 60);
            }

            if ( TimeRequested <= time  ) 
                {
                    cout << "You should take : " ;
                    cout << journeyName << endl;
                    cout << "Total Travel Time : " << time  << endl;
                    cout<<'\n';
                }
                else if ( TimeRequested > time){

                    cout << "None of the journeys are appropiate for the time requested " << endl << "Please try another time" <<endl;
                }

        }
    }
}

I think your if should be:

if ( time <= TimeRequested ) 

that is, you're printing all the journeys which can be completed before the requested time.

Also, since there can be more than one suitable journey you may change your print message as
cout << "You can take : " ; (though its purely a cosmetic change :))

Now, for the case when the requested time is too low and none of the journeys are suitable, you have to consider every journey; so that else part is not what you want.

Instead, have a boolean variable, say, hasSomeJourney and initialize it to false. Then inside that if statement, make it true (because if it reaches inside the if, it has journey(s) that matched the condition).

Now outside the main while (line 46) check whether this variable is true or false and accordingly print out the message (i.e. if its false, no journey satisfied, so print the error message)

@deceptikon: please allow him to make the changes himself this time...don't put up a snippet for him.

@deceptikon: please allow him to make the changes himself this time...don't put up a snippet for him.

He's obviously putting in the effort, and a good example every now and again can be far more enlightening than umpteen posts explaining what changes should be made.

While I appreciate that you have his best interests in mind, the unwritten rule of not doing someone's work for them can be taken to unproductive extremes.

a good example every now and again can be far more enlightening than umpteen posts explaining what changes should be made.

I agree.
I was only asking you to wait till he comes up with his version first. I somehow felt that he was not comfortable making the changes... he didn't even change your variable names to the ones he was originally using... :)

I was only asking you to wait till he comes up with his version first.

I wasn't intending to participate in this thread any longer unless directly addressed (even before your request). So no worries on that front. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.