read data from file into structure ?

T

tvn007

I am using the following code to read data from input file into
structure.
Not sure it is the best way. Please comment or you have better way.
please let me kmow.
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

struct Record_info {
string name;
double midterm;
double quiz;
double final;
}student ;
int main (void){

double grade;

ifstream in ("test2.txt");
string line,word;
while (getline(in,line)){
istringstream anyname(line);

anyname>>student.name>>student.midterm>>student.quiz>>student.final;
grade = student.quiz+ 10;
cout << student.name <<endl;
cout << student.midterm <<endl;
cout << student.quiz <<endl;
cout << student.final <<endl;
cout << "GRADE: "<<grade <<endl;
}
return 0;
}
/////////////////////// test2.txt
///////////////////////////////////////
Tony 90.0 -15.2 98.2
Michael 95.0 17.2 92.2
 
J

John Harrison

I am using the following code to read data from input file into
structure.
Not sure it is the best way. Please comment or you have better way.
please let me kmow.
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

struct Record_info {
string name;
double midterm;
double quiz;
double final;
}student ;
int main (void){

double grade;

ifstream in ("test2.txt");
string line,word;
while (getline(in,line)){
istringstream anyname(line);

anyname>>student.name>>student.midterm>>student.quiz>>student.final;
grade = student.quiz+ 10;
cout << student.name <<endl;
cout << student.midterm <<endl;
cout << student.quiz <<endl;
cout << student.final <<endl;
cout << "GRADE: "<<grade <<endl;
}
return 0;
}
/////////////////////// test2.txt
///////////////////////////////////////
Tony 90.0 -15.2 98.2
Michael 95.0 17.2 92.2

Looks fine to me, apart from the gratuitous use of a global variable.
Try this

struct Record_info {
string name;
double midterm;
double quiz;
double final;
};

int main()
{
...
while (getline(in,line))
{
istringstream anyname(line);
Record_info student;
anyname >> student.name >> student.midterm >>
student.quiz >> student.final;
...
}
...
}

Declare variables locally where you need them, not globally.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Help, read input from file ? 3
Help on struct ? 3
CLASS ? 2
struct ? 5
Rearranging .ply file via C++ String Parsing 0
TF-IDF 1
Reading from a text file, netbeans c++? 2
vector of struct ? 2

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top