By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,431 Members | 1,765 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,431 IT Pros & Developers. It's quick & easy.

read data from file into structure ?

P: n/a
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.qu iz>>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

Nov 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
use a class or a function to do it

Nov 22 '05 #2

P: n/a
tv****@hotmail.com wrote:
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.qu iz>>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
Nov 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.