I'm writing a program that reads a text file and puts it into an array of structs. There can only be one transaction per line in this format:

custNumber firstName lastName numItemsPurchased amtSpent

What I dont understand is how do you put the data in the file into an array of structs?

Hello,

First off, a couple of things have to be known.

1) Do you know how to read in the data and sperate it into just regualar variables?
2) Do you know how to construct a strut variable type?
2) Do you know how to make an array of structs?

What you are asking for is pretty broad, and without out right writing the program for you , you need to say what exactly you are having a problem with.

DKnight764

Ok first...no i'm not sure how to read in the data and separate it and the only thing i know about structs is what i read in the book...

But this is what i have so far:

#include <iostream>
#include <fstream>

using namespace std;

struct custInfo{
  int custNumber, numItems;
  string firstName, lastName;
  float amtSpent;
};

void getData(ifstream &infile, custInfo list[], int listSize);

int main(){
  ifstream infile;
  
  custInfo custList[100];
  int size, input;
  
  infile.open("E:sales.txt");
  
  if(!infile){
    cout<<"Cannot open input file."<<endl;
    return 1;
  }
  getData(input, custList[], size);
 return 0;
}

void getData(ifstream &infile, custInfo list[], int listSize){
  
  for (int i=0; i<100; i++){
    infile>>list[i].custNumber>>list[i].firstName
    	  >>list[i].lastName>>list[i].numItems
          >>list[i].amtSpent;
  }
  
  for (int count=0; count<100; count++){
    cout<<list[count].custNumber<<" "
        <<list[count].firstName<<" "
        <<list[count].lastName<<" "
        <<list[count].numItems<<" "
        <<list[count].amtSpent;
  }
}

I know this isnt right because when i run it nothing happens. It compiles but that's about it. That's how they put the struct into an array in my C++ book and that's the way the got it to print out too.

I have to read in the data from a text file and properly put them in the array. 100 customers is the allowed limit. I figure if i cant get the data into the array then I can finish the rest of the program myself.

This article has been dead for over six months. Start a new discussion instead.