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