Reading Variable by Variable
Lesson 10 of 23 in Coddy's C++ File Handling course.
We can also read variable by variable or by using the >> operator. This is very useful if you are solving a Competitive Programming problem and you have input separated by whitespace or newline, but it could be a problem when reading a whole sentence, since the >> operator is reading until the next whitespace or newline.
ifstream my_file;
my_file.open("example.txt");
string word
while(!my_file.eof()) {
my_file >> word
cout << word << endl;
}As you can see, this is how we read using the >> operator, we create an ifstream, and then we create a string to input every word, we can use a number as well. We again use a while loop to cycle through the file until we reach the end-of-file.
Challenge
EasyUse the >> operator method to input in this problem. The file name is data.txt
On input there will be a name (string), age (int) and GPA (float), print out the following message: The student {name} is {age} years old and has a gpa of {GPA}
Try it yourself
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Enter your code here
return 0;
}All lessons in C++ File Handling
3Reading from Files
Reading from a fileReading Line by LineReading Char by CharReading Variable by VariablePractice Lab #2