Using data files

So I am given a data file with a list of students names and their answers for a given test. How do I read in the file and store the students names and their scores on a test in an array to print it out in a list?

Last edited on
could you post the format of the data file? or a small part of it? you would probably open it with ifstream if you want to try for yourself first.
This is the basic idea of how to read from a file. I tried to comment it so you can understand.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <fstream> //Required for reading in/out of files
#include <iostream>
#include <string>

using std::string; //Edit - Did this out of habit. 
using std::cout;  //It saved zero typing. lol
using std::cin;
using std::ifstream;

int main()
{
    int n = 0; //Just going to be used to go through the array below. 
    string x[5]; //My text file has 5 entries, which I'm going to store in this array. 
    ifstream f ("textfile.txt"); 
    /*
    ifstream opens an in file stream. i.e. We are going to read data from a file. 
    The name of the file goes in brackets. 
    */ 
    while(!f.eof()) //eof() is a member function of our in file stream. It is used
    { //to check if we have reached the end of file yet, so while(not end of file()). 
        getline(f,x); //Extract the line from the file. 
        std::cout << x[n] << "\n"; //Output the line to the appropriate part of the array. 
    }
    return 0;
}


The text file I was reading from:
Name 2ndname 56
Name 2ndname 86
Name 2ndname 90
The  Swat    98 
Name 2ndname 75


As Shadowcool39 said, for more precise guidance, we would need to know the format of the file you're going to read from and the format things are being stored in. For instance, are names going in a string array and their scores in an integer array? Example input/output would be great...
Last edited on
Using the f.eof () function can be very problematic sometimes, be careful when implementing this into your programs.
I have to use typedef that was one of the standards that had to be met.
But it is a data file with the first line being the test answer key followed by the students name and his answers for 25 total students.So,
TFTF
lock , john
FFFF
parasin , max
FFFT
....
the input is strictly from the infile and then the output is :A table giving the list of student names in the order they were read in, the test answers for that student, and the student's test score.
The mean test score.
A histogram showing the number of students who received scores in the following ranges: 0 thru 5, 6 thru 10, 11 thru 15, 16 thru 20, 21 thru 25, and 25 thru 30
Well, all of the input takes the form of strings.
In this case, you could simply use getline() to read each line.
1
2
3
    ifstream fin("filename.txt");
    string name;
    getline(fin, name);
Last edited on
Topic archived. No new replies allowed.