Sara Andrea
Sara Andrea

Reputation: 5

How to read a single line of txt file word by word [C++]

I need to read a single line of a given file word by word. The file is a register of exam grades by different students. In particular, for any student there is a first line formatted as follows:

-name- -surname-

Then, there is a second line reporting the grades of every exam using the following format:

-grade 1- -grade 2- -grade 3- [...] -grade n-

I created a class Student and want to put the grades in an array of int. I know how to read the file word by word, but I have no idea how to stop once the grades from a student are over (since I don't know how may grades any given student has beforehand). I thought to write a while repetition statement, but I have no idea what the condition could be.

Is there a way to read a line word by word and then stop reading once the line is over?

This is what I managed to write until now:

cout << "Inserisci il nome del file da analizzare: " << endl;
cin >> _filename;
fstream myfile;
myfile.open(_filename);  
if (myfile.is_open())  
{
    myfile >> _name >> _surname >> ;  //reading name and surname

}

Upvotes: 0

Views: 54

Answers (1)

R Sahu
R Sahu

Reputation: 206567

  1. Read a line of text using std::getline.
  2. Read each token from the line by using a std::istringstream.

std::string line;
if ( ! std::getline(myfile, line) )
{
   // Problem reading the line.
   // Deal with error.
}
else
{
   // Read line successfully.
   std::istringstream str(line);
   std::string token;
   while ( str >> token )
   {
      // Use token.
   }
}

Upvotes: 1

Related Questions