I am trying to read a file having multiple lines, where each line has a word and then a space followed by a short description of the word.
Example of the text file:
hello A type of greeting clock A device which tells us the time .
The fullstop (.) at the end represents that there are no more lines to read.
I tried an approach using a delimiter in the getline() function, but only succeeded in reading one line of the file. I want to store the first word (before the first space) in a variable, say word, and the description (words after the first space until a new line character is encountered) in another variable, say desc.
My approach:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
    string filename = "text.txt" ;
    ifstream file (filename);
    if (!file)
    {
        cout<<"could not find/open file "<<filename<<"\n";
        return 0;
    } 
    string word;
    string desc;
    string line;
    while(file){
        getline(file,line,' ');
        
        word = line;
        break;
    }
    while(file){
        getline(file,line,'\n');
        desc = line;
        break;
    }    
   file.close();
    cout<<word<<":  ";
    cout<<desc<<"\n";
    return 0;
}
The output of the above code is:
hello:  A type of greeting
I tried adding another parent while loop to the ones written above, having the condition file.eof(), but then the program never enters the two child loops.
 
     
    