Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Reading from File question... [modified]

Reading from File question... [modified]

Scheduled Pinned Locked Moved C / C++ / MFC
questionc++iosdata-structureshelp
24 Posts 6 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L led mike

    q_p wrote:

    I'm new to C++

    Most students are eh?

    q_p wrote:

    Any help would be awesome.

    You create a struct or class that encapsulates the data. Then you use a STL (Standard Template Library) vector to dynamically store each one after it is loaded from the file. Or perhaps a "map" rather than "vector" is called for, depends on requirements.

    led mike

    Q Offline
    Q Offline
    q_p
    wrote on last edited by
    #3

    Thanks Mike. The problem is, I dunno what any of that even is. We haven't learned this stuff at all. I've basically learned if/else, switch, functions, and arrays... the basic stuff. I figured there's gotta be a simple way to do it with these basic tools that I'm just not seeing, because why would my professor give me a project about things she hasn't taught?

    Z L 2 Replies Last reply
    0
    • Q q_p

      Hello. I'm new to C++ so go easy. I'm trying to read from a txt file, but need to do it in a specific way. The txt file will basically be formatted like this:

      1111 90 85 50 78 85
      2222 100 90 99 89 88
      3333 52 85 44 66 87
      4444 87 88 95 85 100

      where the first number of each line will be a student ID number and the next five numbers are grades they got on 5 different tests. I need to read this file as such and then do stuff with that data. What I don't know is how to read the file and store those numbers in a usable way. The thing is I don't know how many lines the file will have, so I need go all the way to the end of the file. Given this, do I have to create an array for the different inputs from the file, and how do I then differentiate between the student ID numbers and the test grades? What I have so far is laughable because I simply don't know how to go about this, but here it is: int id, score1, score2, score3, score4, score5; ifstream inFile; inFile.open ("grade.txt", ios::in); while (!inFile.eof()) { inFile >> id >> score1 >> score2 >> score3 >> score4 >> score5; } inFile.close(); Obviously the while loop isn't done yet because I don't know what to do after I have a line of input from the file. Any help would be awesome. -- modified at 17:27 Wednesday 25th October, 2006

      Z Offline
      Z Offline
      Zac Howland
      wrote on last edited by
      #4

      Here is the most flexible way:

      #include <vector>
      #include <algorothm>
      #include <iterator>
      #include <fstream>
      
      class Student
      {
      	Student() : _StudentID(0) {}
      	~Student() {}
      
      	void setStudentID(long id) {_StudentID = id; }
      	long getStudentID() const { return _StudentID; }
      
      	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
      	std::vector<long>::iterator grades_end() { return _Grades.end(); }
      
      	void addGrade(long grade) {_Grades.push_back(grade); }
      	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
      	unsigned long grade_count() const { return _Grades.size(); }
      private:
      	long _StudentID;
      	std::vector<long> _Grades;
      };
      
      ostream& operator<<(ostream& os, const Student& s)
      {
      	os << s.getStudentID() << " ";
      	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
      	os << endl;
      	return os;
      }
      
      istream& operator>>(istream& is, Student& s)
      {
      	long id;
      	std::vector<long> grades;
      	is >> id;
      	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
      	s.setStudentID(id);
      	s.addGrades(grades);
      	return is;
      }
      
      int main()
      {
      	ifstream fin;
      	fin.open("mydata.txt");
      	std::vector<Student> students;
      	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
      	fin.close();
      }
      

      If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

      L Q S T D 6 Replies Last reply
      0
      • Q q_p

        Thanks Mike. The problem is, I dunno what any of that even is. We haven't learned this stuff at all. I've basically learned if/else, switch, functions, and arrays... the basic stuff. I figured there's gotta be a simple way to do it with these basic tools that I'm just not seeing, because why would my professor give me a project about things she hasn't taught?

        Z Offline
        Z Offline
        Zac Howland
        wrote on last edited by
        #5

        Generally, I wouldn't actually give you as much as I did below, but I'd rather see someone start off on the right foot than to learn bad habits from the start. What is posted below should get you started.

        If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

        1 Reply Last reply
        0
        • Q q_p

          Thanks Mike. The problem is, I dunno what any of that even is. We haven't learned this stuff at all. I've basically learned if/else, switch, functions, and arrays... the basic stuff. I figured there's gotta be a simple way to do it with these basic tools that I'm just not seeing, because why would my professor give me a project about things she hasn't taught?

          L Offline
          L Offline
          led mike
          wrote on last edited by
          #6

          q_p wrote:

          if/else, switch, functions, and arrays

          Well then I guess it will be using arrays since "if/else, switch and functions" can't store any information for you. Good luck! :)

          led mike

          1 Reply Last reply
          0
          • Z Zac Howland

            Here is the most flexible way:

            #include <vector>
            #include <algorothm>
            #include <iterator>
            #include <fstream>
            
            class Student
            {
            	Student() : _StudentID(0) {}
            	~Student() {}
            
            	void setStudentID(long id) {_StudentID = id; }
            	long getStudentID() const { return _StudentID; }
            
            	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
            	std::vector<long>::iterator grades_end() { return _Grades.end(); }
            
            	void addGrade(long grade) {_Grades.push_back(grade); }
            	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
            	unsigned long grade_count() const { return _Grades.size(); }
            private:
            	long _StudentID;
            	std::vector<long> _Grades;
            };
            
            ostream& operator<<(ostream& os, const Student& s)
            {
            	os << s.getStudentID() << " ";
            	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
            	os << endl;
            	return os;
            }
            
            istream& operator>>(istream& is, Student& s)
            {
            	long id;
            	std::vector<long> grades;
            	is >> id;
            	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
            	s.setStudentID(id);
            	s.addGrades(grades);
            	return is;
            }
            
            int main()
            {
            	ifstream fin;
            	fin.open("mydata.txt");
            	std::vector<Student> students;
            	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
            	fin.close();
            }
            

            If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

            L Offline
            L Offline
            led mike
            wrote on last edited by
            #7

            So Zac... back in school again are you? :laugh:

            led mike

            Z 1 Reply Last reply
            0
            • Z Zac Howland

              Here is the most flexible way:

              #include <vector>
              #include <algorothm>
              #include <iterator>
              #include <fstream>
              
              class Student
              {
              	Student() : _StudentID(0) {}
              	~Student() {}
              
              	void setStudentID(long id) {_StudentID = id; }
              	long getStudentID() const { return _StudentID; }
              
              	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
              	std::vector<long>::iterator grades_end() { return _Grades.end(); }
              
              	void addGrade(long grade) {_Grades.push_back(grade); }
              	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
              	unsigned long grade_count() const { return _Grades.size(); }
              private:
              	long _StudentID;
              	std::vector<long> _Grades;
              };
              
              ostream& operator<<(ostream& os, const Student& s)
              {
              	os << s.getStudentID() << " ";
              	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
              	os << endl;
              	return os;
              }
              
              istream& operator>>(istream& is, Student& s)
              {
              	long id;
              	std::vector<long> grades;
              	is >> id;
              	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
              	s.setStudentID(id);
              	s.addGrades(grades);
              	return is;
              }
              
              int main()
              {
              	ifstream fin;
              	fin.open("mydata.txt");
              	std::vector<Student> students;
              	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
              	fin.close();
              }
              

              If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

              Q Offline
              Q Offline
              q_p
              wrote on last edited by
              #8

              Thanks a lot Zac I really appreciate that and can appreciate you not wanting to give me the solution straight up. Normally I can think these things through myself and figure it out, but I was having a serious mental block. After Mike's post though something clicked and I figured it out - I can simply do everything I need to do within the while loop after reading each separate line, so I don't need to store each number separately, I can just store them one line at a time. Basically I was making things a whole lot more complicated than they had to be... Thanks a lot for the replies! It's good to know there are fast replying helpful people here.

              Z T 2 Replies Last reply
              0
              • L led mike

                So Zac... back in school again are you? :laugh:

                led mike

                Z Offline
                Z Offline
                Zac Howland
                wrote on last edited by
                #9

                :laugh: Yeah, I was bored ... and it was the end of the day. Even I can be generous sometimes ...

                If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                1 Reply Last reply
                0
                • Q q_p

                  Thanks a lot Zac I really appreciate that and can appreciate you not wanting to give me the solution straight up. Normally I can think these things through myself and figure it out, but I was having a serious mental block. After Mike's post though something clicked and I figured it out - I can simply do everything I need to do within the while loop after reading each separate line, so I don't need to store each number separately, I can just store them one line at a time. Basically I was making things a whole lot more complicated than they had to be... Thanks a lot for the replies! It's good to know there are fast replying helpful people here.

                  Z Offline
                  Z Offline
                  Zac Howland
                  wrote on last edited by
                  #10

                  While it is useful to know how to write your own loops, most of the time if you are writing your own loops you should rethink your implementation. The STL algorithms do a lot for you and can help simplify your code (once you get use to the template syntax). Depending on what your professor is expecting, you may or may not want to go that route.

                  If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                  1 Reply Last reply
                  0
                  • Z Zac Howland

                    Here is the most flexible way:

                    #include <vector>
                    #include <algorothm>
                    #include <iterator>
                    #include <fstream>
                    
                    class Student
                    {
                    	Student() : _StudentID(0) {}
                    	~Student() {}
                    
                    	void setStudentID(long id) {_StudentID = id; }
                    	long getStudentID() const { return _StudentID; }
                    
                    	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
                    	std::vector<long>::iterator grades_end() { return _Grades.end(); }
                    
                    	void addGrade(long grade) {_Grades.push_back(grade); }
                    	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
                    	unsigned long grade_count() const { return _Grades.size(); }
                    private:
                    	long _StudentID;
                    	std::vector<long> _Grades;
                    };
                    
                    ostream& operator<<(ostream& os, const Student& s)
                    {
                    	os << s.getStudentID() << " ";
                    	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
                    	os << endl;
                    	return os;
                    }
                    
                    istream& operator>>(istream& is, Student& s)
                    {
                    	long id;
                    	std::vector<long> grades;
                    	is >> id;
                    	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
                    	s.setStudentID(id);
                    	s.addGrades(grades);
                    	return is;
                    }
                    
                    int main()
                    {
                    	ifstream fin;
                    	fin.open("mydata.txt");
                    	std::vector<Student> students;
                    	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
                    	fin.close();
                    }
                    

                    If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                    S Offline
                    S Offline
                    Stephen Hewitt
                    wrote on last edited by
                    #11

                    A minor critisism, but I'd add the following: typedef std::vector<long> collection_t; typedef collection_t::value_type value_type; typedef collection_t::iterator iterator; typedef collection_t::const_iterator const_iterator; Then I'd change all methods that return std::vector<long>::iterator to return iterator instead. Also I'd replace the std::vector<long> _Grades; with collection_t. I'd also rename grades_begin to begin and grades_end to end and add const versions which return const_iterators. With all this inplace: - The collection type can be changed in one palce. - Code like the following will work as expected: Student &s = .... Student::iterator i = s.begin(); Student::iterator e = s.end();

                    Steve

                    Z 1 Reply Last reply
                    0
                    • Z Zac Howland

                      Here is the most flexible way:

                      #include <vector>
                      #include <algorothm>
                      #include <iterator>
                      #include <fstream>
                      
                      class Student
                      {
                      	Student() : _StudentID(0) {}
                      	~Student() {}
                      
                      	void setStudentID(long id) {_StudentID = id; }
                      	long getStudentID() const { return _StudentID; }
                      
                      	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
                      	std::vector<long>::iterator grades_end() { return _Grades.end(); }
                      
                      	void addGrade(long grade) {_Grades.push_back(grade); }
                      	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
                      	unsigned long grade_count() const { return _Grades.size(); }
                      private:
                      	long _StudentID;
                      	std::vector<long> _Grades;
                      };
                      
                      ostream& operator<<(ostream& os, const Student& s)
                      {
                      	os << s.getStudentID() << " ";
                      	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
                      	os << endl;
                      	return os;
                      }
                      
                      istream& operator>>(istream& is, Student& s)
                      {
                      	long id;
                      	std::vector<long> grades;
                      	is >> id;
                      	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
                      	s.setStudentID(id);
                      	s.addGrades(grades);
                      	return is;
                      }
                      
                      int main()
                      {
                      	ifstream fin;
                      	fin.open("mydata.txt");
                      	std::vector<Student> students;
                      	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
                      	fin.close();
                      }
                      

                      If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                      T Offline
                      T Offline
                      ThatsAlok
                      wrote on last edited by
                      #12

                      Humm!! his Lecturer might be Seeing this tooo :).. anyway nice code!

                      "Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow

                      cheers, Alok Gupta VC Forum Q&A :- I/ IV Support CRY- Child Relief and You

                      Z 1 Reply Last reply
                      0
                      • Q q_p

                        Thanks a lot Zac I really appreciate that and can appreciate you not wanting to give me the solution straight up. Normally I can think these things through myself and figure it out, but I was having a serious mental block. After Mike's post though something clicked and I figured it out - I can simply do everything I need to do within the while loop after reading each separate line, so I don't need to store each number separately, I can just store them one line at a time. Basically I was making things a whole lot more complicated than they had to be... Thanks a lot for the replies! It's good to know there are fast replying helpful people here.

                        T Offline
                        T Offline
                        ThatsAlok
                        wrote on last edited by
                        #13

                        HI g_p,   i still prefer that you write your own code.. actually Zac code's looks like to be highly proffessional and you as you have said know only basic.. your teacher will caught you very easily.. i my opinion you should read file line by line and use strtok function and atoi function to fetch data from that files!.....   hope you will give the try!

                        "Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow

                        cheers, Alok Gupta VC Forum Q&A :- I/ IV Support CRY- Child Relief and You

                        1 Reply Last reply
                        0
                        • S Stephen Hewitt

                          A minor critisism, but I'd add the following: typedef std::vector<long> collection_t; typedef collection_t::value_type value_type; typedef collection_t::iterator iterator; typedef collection_t::const_iterator const_iterator; Then I'd change all methods that return std::vector<long>::iterator to return iterator instead. Also I'd replace the std::vector<long> _Grades; with collection_t. I'd also rename grades_begin to begin and grades_end to end and add const versions which return const_iterators. With all this inplace: - The collection type can be changed in one palce. - Code like the following will work as expected: Student &s = .... Student::iterator i = s.begin(); Student::iterator e = s.end();

                          Steve

                          Z Offline
                          Z Offline
                          Zac Howland
                          wrote on last edited by
                          #14

                          Agreed, but I had to leave something for his academic exercise ;P

                          If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                          1 Reply Last reply
                          0
                          • Q q_p

                            Hello. I'm new to C++ so go easy. I'm trying to read from a txt file, but need to do it in a specific way. The txt file will basically be formatted like this:

                            1111 90 85 50 78 85
                            2222 100 90 99 89 88
                            3333 52 85 44 66 87
                            4444 87 88 95 85 100

                            where the first number of each line will be a student ID number and the next five numbers are grades they got on 5 different tests. I need to read this file as such and then do stuff with that data. What I don't know is how to read the file and store those numbers in a usable way. The thing is I don't know how many lines the file will have, so I need go all the way to the end of the file. Given this, do I have to create an array for the different inputs from the file, and how do I then differentiate between the student ID numbers and the test grades? What I have so far is laughable because I simply don't know how to go about this, but here it is: int id, score1, score2, score3, score4, score5; ifstream inFile; inFile.open ("grade.txt", ios::in); while (!inFile.eof()) { inFile >> id >> score1 >> score2 >> score3 >> score4 >> score5; } inFile.close(); Obviously the while loop isn't done yet because I don't know what to do after I have a line of input from the file. Any help would be awesome. -- modified at 17:27 Wednesday 25th October, 2006

                            D Offline
                            D Offline
                            David Crow
                            wrote on last edited by
                            #15

                            q_p wrote:

                            where the first number of each line will be a student ID number and the next five numbers are grades they got on 5 different tests.

                            Reminds me of a gradebook program I wrote back in college. There's a lot you can do with this, once you get past the basics.


                            "Approved Workmen Are Not Ashamed" - 2 Timothy 2:15

                            "Judge not by the eye but by the heart." - Native American Proverb

                            1 Reply Last reply
                            0
                            • T ThatsAlok

                              Humm!! his Lecturer might be Seeing this tooo :).. anyway nice code!

                              "Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow

                              cheers, Alok Gupta VC Forum Q&A :- I/ IV Support CRY- Child Relief and You

                              Z Offline
                              Z Offline
                              Zac Howland
                              wrote on last edited by
                              #16

                              ThatsAlok wrote:

                              his Lecturer might be Seeing this tooo

                              Which is why I left plenty for him to do. I just wrote the code to read the file (and even it is incomplete at the moment ... several things should be cleaned up a bit to actually meet professional standards). Typically, students will write code that will read all that data in and store it in several unrelated arrays (that they are relating in their head, but not in code) and do whatever the assignment asks by manipulating that data. This makes the code very unreadable and enforces a horrible habit that will only get worse if not corrected (which is the only reason I offered as much code as I did for this post). As a side note, when I was in college, I actually had a few professors who would count an assignment similar to this one as wrong if the code produced was not up to professional standards. Just some things to keep in mind.

                              If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                              1 Reply Last reply
                              0
                              • Z Zac Howland

                                Here is the most flexible way:

                                #include <vector>
                                #include <algorothm>
                                #include <iterator>
                                #include <fstream>
                                
                                class Student
                                {
                                	Student() : _StudentID(0) {}
                                	~Student() {}
                                
                                	void setStudentID(long id) {_StudentID = id; }
                                	long getStudentID() const { return _StudentID; }
                                
                                	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
                                	std::vector<long>::iterator grades_end() { return _Grades.end(); }
                                
                                	void addGrade(long grade) {_Grades.push_back(grade); }
                                	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
                                	unsigned long grade_count() const { return _Grades.size(); }
                                private:
                                	long _StudentID;
                                	std::vector<long> _Grades;
                                };
                                
                                ostream& operator<<(ostream& os, const Student& s)
                                {
                                	os << s.getStudentID() << " ";
                                	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
                                	os << endl;
                                	return os;
                                }
                                
                                istream& operator>>(istream& is, Student& s)
                                {
                                	long id;
                                	std::vector<long> grades;
                                	is >> id;
                                	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
                                	s.setStudentID(id);
                                	s.addGrades(grades);
                                	return is;
                                }
                                
                                int main()
                                {
                                	ifstream fin;
                                	fin.open("mydata.txt");
                                	std::vector<Student> students;
                                	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
                                	fin.close();
                                }
                                

                                If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                                D Offline
                                D Offline
                                David Crow
                                wrote on last edited by
                                #17

                                Nice example, Zac. It's quite informative.

                                Zac Howland wrote:

                                _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end());

                                The compiler complains with: error C2664: 'void __thiscall std::vector >::insert(long *,unsigned int,const long &)' : cannot convert parameter 1 from 'class std::back_insert_iterator > >' to 'long *'


                                "Approved Workmen Are Not Ashamed" - 2 Timothy 2:15

                                "Judge not by the eye but by the heart." - Native American Proverb

                                Z 1 Reply Last reply
                                0
                                • D David Crow

                                  Nice example, Zac. It's quite informative.

                                  Zac Howland wrote:

                                  _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end());

                                  The compiler complains with: error C2664: 'void __thiscall std::vector >::insert(long *,unsigned int,const long &)' : cannot convert parameter 1 from 'class std::back_insert_iterator > >' to 'long *'


                                  "Approved Workmen Are Not Ashamed" - 2 Timothy 2:15

                                  "Judge not by the eye but by the heart." - Native American Proverb

                                  Z Offline
                                  Z Offline
                                  Zac Howland
                                  wrote on last edited by
                                  #18

                                  hmm, looks like it is trying to call the single insert instead of the bulk insert. You can change it (without too much efficiency loss) to:

                                  copy(grades.begin(), grades.end(), back_inserter(_Grades));
                                  

                                  What STL implementation are you using by chance?

                                  If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                                  D 1 Reply Last reply
                                  0
                                  • Z Zac Howland

                                    hmm, looks like it is trying to call the single insert instead of the bulk insert. You can change it (without too much efficiency loss) to:

                                    copy(grades.begin(), grades.end(), back_inserter(_Grades));
                                    

                                    What STL implementation are you using by chance?

                                    If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                                    D Offline
                                    D Offline
                                    David Crow
                                    wrote on last edited by
                                    #19

                                    Zac Howland wrote:

                                    What STL implementation are you using by chance?

                                    I do not know. It's the one that ships with VC++ v6.


                                    "Approved Workmen Are Not Ashamed" - 2 Timothy 2:15

                                    "Judge not by the eye but by the heart." - Native American Proverb

                                    Z 1 Reply Last reply
                                    0
                                    • D David Crow

                                      Zac Howland wrote:

                                      What STL implementation are you using by chance?

                                      I do not know. It's the one that ships with VC++ v6.


                                      "Approved Workmen Are Not Ashamed" - 2 Timothy 2:15

                                      "Judge not by the eye but by the heart." - Native American Proverb

                                      Z Offline
                                      Z Offline
                                      Zac Howland
                                      wrote on last edited by
                                      #20

                                      Actually, I think I know why it might have done that. Since the old Dinkumware implementation used pointers as iterators (basically, typdef a pointer to iterator for a given container) for many of the containers, it probably couldn't easily figure out that it should call the bulk instead of the single. I'm not 100% sure on that, but I was able to reproduce it with an older gcc implementation. Another alternative is to use the insert algorithm which only takes iterators. However, copy works for this case.

                                      If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                                      1 Reply Last reply
                                      0
                                      • Z Zac Howland

                                        Here is the most flexible way:

                                        #include <vector>
                                        #include <algorothm>
                                        #include <iterator>
                                        #include <fstream>
                                        
                                        class Student
                                        {
                                        	Student() : _StudentID(0) {}
                                        	~Student() {}
                                        
                                        	void setStudentID(long id) {_StudentID = id; }
                                        	long getStudentID() const { return _StudentID; }
                                        
                                        	std::vector<long>::iterator grades_begin() { return _Grades.begin(); }
                                        	std::vector<long>::iterator grades_end() { return _Grades.end(); }
                                        
                                        	void addGrade(long grade) {_Grades.push_back(grade); }
                                        	void addGrades(const std::vector<long>& grades) { _Grades.insert(back_inserter(_Grades), grades.begin(), grades.end()); }
                                        	unsigned long grade_count() const { return _Grades.size(); }
                                        private:
                                        	long _StudentID;
                                        	std::vector<long> _Grades;
                                        };
                                        
                                        ostream& operator<<(ostream& os, const Student& s)
                                        {
                                        	os << s.getStudentID() << " ";
                                        	copy(s.begin(), s.end(), ostream_iterator<long>(os, " "));
                                        	os << endl;
                                        	return os;
                                        }
                                        
                                        istream& operator>>(istream& is, Student& s)
                                        {
                                        	long id;
                                        	std::vector<long> grades;
                                        	is >> id;
                                        	copy(istream_iterator<long>(is), istream_iterator<long>(), back_inserter(grades));
                                        	s.setStudentID(id);
                                        	s.addGrades(grades);
                                        	return is;
                                        }
                                        
                                        int main()
                                        {
                                        	ifstream fin;
                                        	fin.open("mydata.txt");
                                        	std::vector<Student> students;
                                        	copy(istream_iterator<Student>(fin), istream_iterator<Student>(), back_inserter(students));
                                        	fin.close();
                                        }
                                        

                                        If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                                        D Offline
                                        D Offline
                                        David Crow
                                        wrote on last edited by
                                        #21

                                        Zac, I was going back over this code and was confused on a few things. In main(), the call to copy() is made once for the entire file. This, in turn, is supposed to call operator>> once for each line of the file. Is that correct? Using the debugger, I see operator>> getting called only for the first line of the file. I'm not seeing the students vector grow at all. What am I missing? Thanks, DC


                                        "A good athlete is the result of a good and worthy opponent." - David Crow

                                        "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

                                        Z 1 Reply Last reply
                                        0
                                        • D David Crow

                                          Zac, I was going back over this code and was confused on a few things. In main(), the call to copy() is made once for the entire file. This, in turn, is supposed to call operator>> once for each line of the file. Is that correct? Using the debugger, I see operator>> getting called only for the first line of the file. I'm not seeing the students vector grow at all. What am I missing? Thanks, DC


                                          "A good athlete is the result of a good and worthy opponent." - David Crow

                                          "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

                                          Z Offline
                                          Z Offline
                                          Zac Howland
                                          wrote on last edited by
                                          #22

                                          Looking back at it, is a slight bug in my example code. Basically, since the id's and grades are both longs, there is no way to tell them apart. It would probably be helpful to modify the output slightly by putting a grade count in between the student id and the first grade so that you can modify the copy call (for obtaining the grades) to just grab that many items (instead of grabbing everything that is left in the file). Another (possibly simpler alternative) would be to grab the student id, and then use getline to obtain the rest of the line, place that string into a stringstream and then call copy on it (this solution has the added benefit of not having to change the input/output file format).

                                          If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

                                          D 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups