-2

there is my code for reading data from text file, i want this code to read data line by line from text file, currently its just reading first line of my text file, and not going to next line. "Students" is text file. and text file contains data given below,

[ALI,DBA,BITF11M001,3.0,3.57

ASIF,DBA,BITF11M002,3.5,3.9

ALI,OOP,BITF11M001,3.5,3.57

ASIF,OOAD,BITF11M002,3.7,3.9

ALI,OOAD,BITF11M001,3.5,3.57

ASIF,OOP,BITF11M002,4.0,3.9

ALI,DSA,BITF11M001,3.0,3.57

ASIF,DSA,BITF11M002,4.0,3.9 ]

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

struct student_attribute 

{
    string name [20];
    string course [20];
    string roll_no[20];
    float GPA [20];
    float CGPA [20];

};

int main () 

{
    int i =0;

    int count ;

    student_attribute data;

    ifstream myfile ("Students.txt");   


   string line;

        while (myfile)

    {
        getline(myfile, data.name[i], ',');

        getline(myfile, data.course[i], ',');

        getline(myfile, data.roll_no[i], ',');

        myfile >> data.GPA[i];

        myfile >> data.CGPA[i]; 

        count++;
    }


    myfile.close();

    for(int index = 0; index < count; index++) 

    {
        cout << data.name[index] << " ";
    }

    for(int index = 0; index < count; index++) 

    {
        cout << data.course[index] << " ";
    }

    for(int index = 0; index < count; index++) 

    {
        cout << data.roll_no[index] << " ";
    }

        for(int index = 0; index < count; index++) 

    {
        cout << data.GPA[index] ;
    }

  return 0;
}
ams
  • 22,492
  • 4
  • 47
  • 71
  • You never change the value of `i` in your loop so you read everything into the same array element – Galik Mar 08 '16 at 12:52
  • It would generally make more sense to have an array of `student_attribute` than a `student_attribute` that has every member being an array. – crashmstr Mar 08 '16 at 12:53
  • `while (myfile)` suffers from the same issues as [`while(!myfile.eof())`](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Mar 08 '16 at 12:53

1 Answers1

1
    myfile >> data.GPA[i];

This will work, reading the number 3.0 from input. The next unread character is ','.

    myfile >> data.CGPA[i]; 

This will not work, because ',' is not a float. Matching failed, the failbit is set for myfile, while ( myfile ) is false, the loop ends.

There are several other problems with your code, some of which were already commented on, but this is the reason why only (part of) the first line is actually read.

DevSolar
  • 59,831
  • 18
  • 119
  • 197