In: Computer Science
so i want to read in a file. just to keep it simple, the text file has student name and the grade, separated by a space. let's say there are 192 student's name and I want to read them in and made them into a Student /object class, which has a constructor, student(string name, int grade). individually creating them seems pain in the ass. reading in should work for any number of names.
So how do I do this in c++?
Please find the CPP program to read and display the student details.
Program:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
/*class to stote student marks and grades*/
class student
{
public:
string name;
int grade;
//only a constructor to store the name and grade
student(string nam, int grad)
{
name=nam;
grade=grad;
}
};
int main(int argc, char **argv)
{
vector<student> all;
string name;
int grade;
ifstream myfile (argv[1]);
//validation for cmd line arguments
if(argc != 2)
{
cout <<"Usage: "<<argv[0]<<"<input
filename>"<<endl;
return -1;
}
/* read the file line by line */
if (myfile.is_open())
{
while ( myfile>>name>>grade )
{
//pass it to new object std1
student std1(name, grade);
//using vectors to populate the student name and grade
all.push_back(std1);
}
//close the text file
myfile.close();
}
else
{
cout << "Unable to open file";
return -1;
}
cout <<"Following are the student details from file:
"<<argv[1]<<endl;
for (int i=0; i<all.size(); i++)
{
cout << all[i].name<<"
"<<all[i].grade<<endl;
}
return 0;
}
Sample Input file:
Irving 2
James 2
fdsdf 23
sdfsd 123
reer 123
sdfsdf 23
sdfsd 213
Output:
USER>./a.out studentMark.txt
Following are the student details from file: studentMark.txt
Irving 2
James 2
fdsdf 23
sdfsd 123
reer 123
sdfsdf 23
sdfsd 213
Screen Shot: