Q:

How to get a specific word from a text file in c++?

I am trying to get a specific word from a .txt file content. Let say, I have a .txt file:
cottage.txt
1 [1] Cottage1 1000 01-10-2019 Free
2 [2] vottage2 2000 01-20-2019 Free

I want to get the word 1000 when I select the line with an ID of (1) or get the word 2000 with an ID of (2) depending on the user input.
My Code: - I know this is incomplete but I just to show what I have tried so far.
string GetWord(string filename)
{
    string word;
    string selectline;

    ifstream fin;
    fin.open(filename);
    cout << "Select which line to get a word from: "; //select line
    cin >> selectline;

    //some code here......

    temp.close();
    fin.close();

    return word;  
}

A:

If the format of every line in the text file is same, then you can try this code-
string GetWord(string filename)
{
    string word, line;
    int selectline;

    ifstream fin(filename.c_str());

    cout << "Select which line to get a word from: "; //select line
    cin >> selectline;

    int i = 1;
    while (getline(fin, line))
    {
        if(i == selectline){
            istringstream ss(line);
            for (int j=0; j<4; j++){
                ss >> word;
            }
            break;
        }
        i++;
    }

    return word;
}

Please let me know if you still have the problem :)

