Drizzt Do'Urden
Drizzt Do'Urden

Reputation: 31

reading values into struct of arrays

I need to create an array of struct with the struct being a student (with data types string FirstName, string LastName, int testScore, and char Grade). I have the logic figured out for the function prototypes, and I have learned a little bit of basic file i/o. I want 20 students in the array of structs, and the info is to be read in from .txt files. This is where I am having trouble. Here is my basic code.

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std; 

struct studentType {
   string firstName;
   string lastName; 
   int testScore; 
   char Grade; 
};

int main()
{
   studentType students[20];

   int i;

   ifstream inputFile; 
   inputFile.open("testScores.txt"); 

   for (i = 0; i < 20; i++)
      inputFile >> students->testScore; 

   cout << "The test scores entered are: "; 

   for (i = 0; i < 20; i++)
      cout << " " << students->testScore; 

   return 0;
}

Upvotes: 0

Views: 149

Answers (1)

Arnav Borborah
Arnav Borborah

Reputation: 11769

You forget to index the element from the array when you access the array. Change:

students->testScore

To:

students[i].testScore

In both loops. The first version only does the changes to the first element (Since it can be accessed with *students), while the second adds the index to the pointer.

This is just another good reason to use std::vector or std::array since if you tried to dereference them as you did with the array here, you would get an obvious error.

On a side note, in C++, you should declare your loop variables inside your loops. Declaring them outside is something that used to be necessary before C99, but not C++.

Upvotes: 2

Related Questions