How to read data from textfile and push in array

Hi there…

1stly sorry for the novice and beginner question but I really need help since I’ve been get fiddling to figure out the error but still have no idea whats wrong with it…here are’s the code I’m using



#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MaxSize 100
#define MaxFound 30

class List{

    int element;
    int index;
    int myList[MaxSize];
    char __filename[50];

    public:
    List(char filename[50]){

        strcpy(__filename,filename);

    }

    int readFile(){
        element = 0;
        index = -1;
        FILE *datafile;
        int i=0;

        datafile = fopen(__filename,"r");
        while((!feof(datafile))&&(i<MaxSize)){
                fscanf(datafile,"%d",&myList*.element);
                myList*.index = i;
               i++;
        }//end while
        return i;
    }

    //%d --> integer
    //%f -->float
    //%s -->string


    void displayList(int MySize){
        int j;

        cout<<"
";
        for(j=0;j<MySize;j++){
            cout<<myList[j].element<<"  "<<endl;;
        }
    }


}; //end clas



main(){

      int fileSize;

      List obj1("senarai.txt");
      fileSize = obj1.readFile();
      obj1.displayList(fileSize);

      return 0;
}



So I really need help since I’m still beginner in C++ hoep someone can shed some light to me at least tell me whats wrong with this code…I’m also attach an image of the error that keep coming pop up to me…same error…

You’ve declared the integer array myList and then tried to point to a member property (element) of this integer…of course integers don’t have members…!


 fscanf(datafile,"%d",&myList*.element);

Not sure what you wanted to do here…are you trying to place the character into the myList array? If so just remove the .element part, it’s an array of ints!

Okay 1stly sorry for the lateness replt and also thanks for the reply and feedbacks…Okay…actually what I try to acieve is how to feed array with different datatype in my case…because I read data from txt file into array here’s are my texfile format

john 30
matt 40
michael 50

so how to feed the array with this two datatype I mean char and integer…load from textfile…I’ve been reading about vector but it seems I cant use it because currently I’m using borland c++ V4.5 therefore I cant include vector.h in my program…so I really need help in how to ahieve it at least tell me the rite path…any help are really appreciated

tq in advanced…

I think you were doing ok but you just have a few syntax errors!

Here’s how i would do it if i was you. Do not use iostream**.h** - their obsolete! Only use .h if there’s no way to avoid it, it’s C headers, not C++ headers!


#include <iostream>
#include <fstream>
#include <sstream>
#include <list>

using namespace std;

// Structure for containing data of multiple datatypes
struct Person {
    string Name;
    int Age;
};

// Needed to signal an error
struct PersonsException {};

class Persons {

    private:
        string m_Filename; // Contains filename
        ifstream m_FileStream; // Contains file
        list<Person> m_List; // List for storage

    public:
        Persons(string Filename) { m_Filename = Filename; }
        int readFile();
        void displayList();
};

int Persons::readFile() {
    
    
    // Open file in filestream
    m_FileStream.open(m_Filename.c_str());
    
    // If no file open, throw an exception - function is terminated
    if (!m_FileStream.is_open()) throw PersonsException();
    
    // Read lines until end of file is reached
    while (!m_FileStream.eof()) {
          string Line;
          
          // Read line from file and put into string
          getline(m_FileStream, Line);
          
          // If string is empty, ignore it
          if (Line.empty()) continue;
          
          // Put string into input stringstream          
          istringstream Stream(Line);
          
          // Create a structure object to use for storing the data
          Person Entry;
          
          // Extract data from istringstream and put into structure         
          Stream >> Entry.Name >> Entry.Age;
          
          // Add structure to list
          m_List.push_back(Entry);
    }
    
    // Return size of the list
    return m_List.size();
}

void Persons::displayList() {
    // Ready iterator for list
    list<Person>::iterator i;
    
    // Iterate through the list
    for ( i = m_List.begin(); i != m_List.end(); ++i) {
        // Print each entry of the list
        cout << i->Name << i->Age << endl;
    }
}



int main(int argc, char **argv) {
    // Try the class out
    try {
        Persons obj1("senarai.txt");
        obj1.readFile();
        obj1.displayList();
    }
    // Oops, an error was thrown
    catch (PersonsException &e) {
          cout << "An error occured - file may not exist." << endl;      
    }
 
    system("pause");
    
    return 0;
}

I have discarded all your C code, and replaced it with C++ code. You shouldn’t be using char arrays, fscanf and whatnot, it’s C functionality. The C++ functionality offers you many more features, and its guaranteed to work with other C++ functionality.

I’m using a structure to contain the name and age, and then store those structures inside a STL list. It’s better to use STL containers than your own arrays, as they are dynamically reallocated when data is added, thereby being unable to overflow. They also have a lot of functionality, and is guaranteed to work.

Another thing - do not use large functions as inline in classes, its unwise. The general rule is to only have very fast and small code inline, and all other code defined outside the class. It does matter, although i cannot give you a throughout explanation. You can read about it here: http://en.wikipedia.org/wiki/Virtual_table

By using C++ methods and STL containers, you’ll end up with an easier class - its unwise for a class to return its size, and to print out from that size. What if the size is larger than your array? It would cause an overflow.

Happy coding :slight_smile: I suggest you read up on C++ methods and STL containers, they’re really helpful. http://www.cplusplus.com/ is a great resource for all everything (standard) C++.

EDIT:
The textfile is formatted like this for my code: (I don’t know if yours was intended as such)


Peter 47
Ervin 36

Sorry for the lateness reply Surrogate…

ermm thanks for walkthrough mate…but once again I guess I have to uninstall my borlandc++4.5 since it’s doesnt have the list library…must strive to make it done hehe once again big thanks mate…:slight_smile: for ur generousity…

**charleh: **thanks to u too mate since u;re really concern and really helpful…:slight_smile:

You can use Microsoft Visual Studio, or one of the open-source mingw editors. I’ve used Dev-C++, but it’s using a very outdated version of mingw. I’m trying Eclipse C++ now, with the latest mingw compiler. But there’s a buttload of free C++ editors out there :slight_smile:

Yeah Visual Studio Express is free now, it’s pretty decent it’s just missing support for MFC and a few other bits and pieces, but you don’t really need those as you aren’t using controls/managing windows