Hi guys I'm trying to do a while loop since this afternoon for the code below but was unsuccessful. I'm reading from a file A family name and the number then the names belong to the family which will be like this
JAMES SMITH
MARY SMITH
JOHN SMITH

ROBERT JOHNSON
PATRICIA JOHNSON
MICHAEL JOHNSON
LINDA JOHNSON
WILLIAM JOHNSON
It reads the first one then stop. what is the best way to do the loop in this case:
I have a header file but I don't think there is a problem with it so I didn't include the file.
Here is a sample from the file that I'm reading from
-------------------------
SMITH 3
JAMES
MARY
JOHN
JOHNSON 4
PATRICIA
MICHAEL
LINDA
WILLIAM

-------------------------

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


int main()
{
    int i=0;
    int size;
	string family;

	ifstream fin("all.txt");
    ofstream fout("OUT.txt");
	int j=0;
	fin>>family;
    fin >> size;
    dynamicArrayClass myArray(size) ;
    while(i<size && fin >> myArray[i])
        i++;
    for(i=0;i<myArray.getNumNames();i++)
        cout << myArray[i] << " "<<family<<endl;

    return 0;
}

I would start by reading a whole line at a time, then checking to see if it contains a space(s) and number at the end. if it does then set variable size to that number and read that many names.

>>dynamicArrayClass myArray(size)
That won't work because it will allocate only enough space (hopefully) for the first set of names. You didn't post the code to dynamicArrayClass so can't say much more about it. If you used the standard c++ template <vector> the allocations would be taken care of for you and the array will grow as you add items to it.

vector<string> array;
// read a string not shown
array.push_back(name);
// read another string  not shown
array.push_back(name);
// etc. etc

In order for your dynamicArrayClass class to work it would have to have a resize method that will expand (or contract) the array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.