Finding a specific line from text file

Hey guys im trying to find a specific line or word from a text file and i cant seem to figure out how to do that. Now i want to find the destination from a text file the destination can be for example New York, Washington,or Texas now i want to read from the text file and find one of these destinations and by that i mean that the user will pick one of the above mentioned destinations which is then stored in a text file and then i need to read from the text file and store it in a string variable and display it. Here is what i have so far..

1
2
3
4
5
6
7
8
9
10
11
// Creating a ifstream object to read from the text file data.txt...
    ifstream readFromFile("Data.txt",ios::in);

    // Creating a string variable.
    string data;

    while(!readFromFile.eof()){ // I cant figure out what to add here so that the code will find and store the destination.
        getline(readFromFile,data);
    }

    cout << data;
You could try strcmp: http://www.cplusplus.com/reference/clibrary/cstring/strcmp/

It's from cstring, so I don't know if it would work with a c++ string, I usually steer away from IOstream and towards cstdio, it's faster and in my opinion, easier to work with.
Or you could try the .find() member function:
http://www.cplusplus.com/reference/string/string/find/
Any other ideas ? these don't really look so helpful.
They are helpful. They are good solutions (the string find() member function is the better choice for your level). Why don't you like them?
Last edited on
because i think you cant use it when reading from a text file maybe an example of it being used would be good.
you don't need ios::in for ifstream because that is the default
hmm yes i do know that just typed it anyway i guess next time i wont.
just letting you know
Thank you. Now would anyone here give me an example on how to use that find function to find a line in a text file?
Something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
string Destinations[3] = {"New York", "Washington", "Texas"};
// Creating a ifstream object to read from the text file data.txt...
    ifstream readFromFile("Data.txt");

    // Creating a string variable.
    string data;

    while(!readFromFile.eof()){ // I cant figure out what to add here so that the code will find and store the destination.
        getline(readFromFile,data);

        for (int i = 0; i < 3; i++)
                if (data.find(Destinations[i])!=string::npos) cout << Destinations[i] << endl;
    }
That worked pretty well thanks. Now i get how to use the find function thanks for that too.
Topic archived. No new replies allowed.