read text file into a structure

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dkwan
    New Member
    • Feb 2008
    • 13

    read text file into a structure

    Hello!
    i have the following data in a file

    student_id student_name maths_score english_score physics_score

    can i use a nested structure to read the file?
    Code:
        
    struct student
    {	int id;
    	char name[40];
    };
    struct score
    {	int maths;
    	int english;
    	int physics;
    };
    if yes, how will i read the file into the structure?help me please
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    What is the format of your input file?

    You can't read a file into anything unless you know what you are reading.

    Comment

    • boxfish
      Recognized Expert Contributor
      • Mar 2008
      • 469

      #3
      If the input file just consists of these numbers and the string, all seperated by whitespace, can you just declare an object of both your structure types, and read into each of their member variables with the >> operator? Or maybe the problem is more complicated than I thought.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        If the string has one word, then you can use the >> operator and just read into some temporary variables:
        [code=cpp]
        cin >> tempint >> tempfloat >> tempstring;
        [/code]

        Theh write a funciton that takes these as arguments and returns a pointer to your struct variable. The funciton creates the struct variable on the heap., populates the members and returns the address of the struct variable.

        You then write a free() that takes the address of the struct variable and frees memory.

        Comment

        Working...