Need help with arrays!!

May 1, 2017 at 8:48pm
I know this sounds so dumb but I just don't know what should I do with it.
So I need to read some data from a txt file, there are some names and integers on each line. Like this
Robert 80 90 100 90 80 76 90 90 100 80 85

My question is how to read the names and integers separately and store them in arrays.


Last edited on May 1, 2017 at 8:52pm
May 1, 2017 at 8:59pm
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 <string>
#include <fstream>
using namespace std;

const int MAX_STUDENTS = 10;
const int MAX_SCORES = 11;

struct Student
{   string name;
    int scores[MAX_SCORES];
};
    
int main ()
{   ifstream infile ("data.txt");
    int     count = 0;
    Student student[MAX_STUDENTS];
        
    while (count < MAX_STUDENTS)
    {   //  Read a name
        if (! (infile >> student[count].name))
            break;      //  eof
        for (int i=0; i<MAX_SCORES; i++)
            infile >> student[count].scores[i];
    }            
}

May 1, 2017 at 9:16pm
Hi,thank you for your quick reply. I am wondering is there any method that will do the same thing without using struct. Thank you!
May 2, 2017 at 2:25pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <fstream>
using namespace std;

const int MAX_STUDENTS = 10;
const int MAX_SCORES = 11;
  
int main ()
{   ifstream infile ("data.txt");
    int     count = 0;
    string names[MAX_STUDENTS];
    int scores[MAX_STUDENTS][MAX_SCORES];
        
    while (count < MAX_STUDENTS)
    {   //  Read a name
        if (! (infile >> names[count]))
            break;      //  eof
        for (int i=0; i<MAX_SCORES; i++)
            infile >> scores[count][i];
    }
    return 0;           
}

Last edited on May 2, 2017 at 2:26pm
Topic archived. No new replies allowed.