Thread: use vectors to read a file and then print info.

  1. #1
    Registered User
    Join Date
    Oct 2016
    Posts
    2

    use vectors to read a file and then print info.

    Hi, I have written part of this code but I am having trouble with some things that I dont know are missing. The requirement of the code is below:


    Your program must include the following:
    Implement all the class methods defined above
    Must initialize the class object variable with initial value in the default constructor
    Your program will read a file contains person’s info. The file has the following format:




    FirstName LastName Sex BirthYear BirthMonth BirthDay








    The file name must (sample file: personsInfo.txt personsInfo.txt) be passed in when you start the program using argc, argv: main (int argc, char* argv[])
    After reading the file, your program will have an user’s menu similar to the one below:
    Enter person’s information:
    Print out person’s information
    Exit


    If user selects “1”, the program will search person’s last name, and if found, will print out person’s information. (Search for Clinton, Trump, Obama). If not found, output a message indicate the person’s information is not found. (search Bush)




    If user selects “2”, the program will print out all the person’s information have entered so far (which is stored in a vector). After prints out all the person’s information, the program will print out the menu again and waiting for user’s input.
    If user selects “3”, the program will exit. Class: Class section name (CS-106-02 or CS-106-03) Your program submission:
    Pdf file contains all of the following:


    What I have so far is below. I would appreciate it if you guys could help me understand and finish the code.


    PersonInfo.txt
    Code:
    Hillary Clinton F 1947 10 26
    Donald Trump M 1946 06 14
    Bernie Sanders M 1941 09 08
    Barack Obama M 1961 08 04
    Melania Trump F 1970 04 26
    Michelle Obama F 1964 01 17

    Okay so after working on the program and trying my best to fix all compiler issues I got to my best but I am having trouble on how I read my file using a vector in the program, and also what I need in some of the functions in the person.cpp file.


    Attaching code below:


    Pleae guide on how to fix it.


    Code:
    #include <cctype>
    #include <iostream>
    #include <vector>
    #include <string>
    #include "Person.h"
    using namespace std;
    
    
    void printMeFirst();
    
    
    void promptUserForInput( vector<Person> &people )
    {
        string firstName;
        /*string lname;
        string sex;
        int byear;
        int bmth;
        int bday;*/
    
    
        cout << "Enter the first name: ";
        cin >> ws;
        getline( std::cin , firstName );
    
    
        while( !isalpha(firstName[0]) ) 
        {
            cout << "Invalid Name!\n"
                 << "Re-enter your name: ";
            getline( std::cin , firstName );
        }
       }
    
    
    void printInformation(const vector<Person> &people)
    {
        for( const auto &person : people ) 
        {
            person.printPerson();
        }
    }
    
    
    
    
    int main(int argc, char *argv[])
    {
    	printMeFirst();
    	
    	std::vector<Person> people;
        int choice = 0;
        
         while( people.size() < 30 && choice != 3 ) 
         {
            std::cout << "Menu\n\n";
            std::cout << "1. Enter Personal Information\n"
                      << "2. Print personal information\n"
                      << "3. Exit\n"
                      << "Enter your choice: ";
            std::cin >> choice;
    	
    	
            if( choice == 1 ) 
            {
                promptUserForInput( people );
            }
            else if( choice == 2 ) 
            {
                printInformation( people );
            }
            else if( choice == 3) 
            {
                std::cout << "\nGoodBye";
            }
            else 
            {
                std::cout << "\nInvalid Choice\n";
            }
        }
       
    	if (argc != 2 )
    	{
    	    std::cout << "usage " << argv[0] << " fname\n";
    	    return 1;
    	}
    	else
    	{
    	    std::cout << "The program will print the follwoing data " << argc << " as entered\n";
    	    std::cout << "The name enter was " << argv[0] << std::endl;
                std::cout << "The info is " << argv[1] << std::endl;
    	}
    
    
    return 0;
    }



    [/code]
    person.cpp
    Code:
    #include <cctype>
    #include <iostream>
    #include <vector>
    #include <string>
    #include "Person.h"
    #include <fstream>
    using namespace std;
    
    
    Person::Person()
    {
    	firstName = "";
    	lastName = "";
    	sex = "";
    	birthYear = 0;
    	birthMonth = 0;
    	birthYear = 0;
    }
    
    
    Person::Person(std::string fname, std::string lname , string s, int byear, int bmth, int bday)
    {
    	firstName = fname;
    	lastName = lname;
    	sex = s;
    	birthYear = byear;
    	birthMonth = bmth;
    	birthDay = bday;
    }
    
    
    std::string Person::setName() const
    {
    	return firstName;
    	return lastName;
    }
    
    
    std::string Person::setSex()
    {
    	return sex;
    }
    
    
    int Person::getbirthInfo() const
    {
    	return birthYear;
    	return birthMonth;
    	return birthDay;
    }
    
    
    std::string Person::findName() const
    {
    	return lastName;
    	return firstName;
    }
    
    
    void Person::read(string lname)
    {
    	ifstream in;
    	string line;
    	bool more = true;
    	in.open (firstName.c.str());
    	while (more)
    	{
    		std::in >> w;
    		if(in.fail())
    		more = false;
    	else
    	{
    		lname.push_back(w);
    		getline (in, line);
    		line.push_back(line);
    	}
    }
    in.close();
    		
    }
    
    
    bool Person::find (std::string a && std::string f)
    {
    	{
    		for (int i=0;i< fname.size();i++)
    		{
    			if (a==firstName[i])
    			{
    				f = info[i]
    				return true;
    			}
    		}
    		return false;
    				
    }
    
    
    void Person::printPerson () const
    {
    	for (i=0;i<firstName.size();i++)
    	{
    		std::cout << firstName[i] << "\t";
    		std::cout << line[i] << "\n";
    	}
    }
    person.h


    Code:
    #ifndef PERSON_H_INCLUDED
    #define PERSON_H_INCLUDED
    #include <string>
    
    
    //The code below was provided during the lab.
    
    
    class Person
    {
    	public:
    		Person();
    		Person(std::string fname, std::string lname , std::string s, int byear, int bmth, int bday );
    		std::string findName (std::string lname) const;
    		void setName (std::string fname, std::string lname);
    		void setSex (std::string s);
    		void setBirthInfo ( int byear, int bmth, int bday);
    		void read (std::string lname);
    		void printPerson () const;
    		bool find (std::string a, std::string f) const;
    		//void setAge( int age );
    		//int getAge() const;
    		//void print() const;
    
    
    	private:
    		std::string firstName;
    		std::string lastName;
    		std::string sex;
    		int birthYear;
    		int birthMonth;
    		int birthDay;
    		
    };
    
    
    #endif // PERSON_H_INCLUDED

    the FILE that i have to make the program read is in the original post at the very top. Take a look at that

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think your biggest problem is with your get and set functions. Some of that is obviously wrong. In your Person class header file, these functions, for example, don't return a value:
    Code:
            void setName (std::string fname, std::string lname);
    
            void setSex (std::string s);
    
            void setBirthInfo ( int byear, int bmth, int bday);
    Yet in your implementation (CPP file) you have coded these functions returning values, often more than one, which is a mistake. In general though, the point of the set function is to change part of the object. Take for example setBirthInfo(). If we assume that dates are valid, then the code is simple:
    Code:
    void Person::setBirthInfo( int byear, int bmth, int bday )
    {
        birthYear = byear;
        birthMonth = bmth;
        birthDay = bday;
    }
    For get functions, you do return internal values, but you cannot return more than one value from a function in C++. So, in your person class, when you return someone's name from a function, you will have to glue the first and last name together in a long string and return that. The date needs a similar operation applied to it to make it one whole Date instead of three numbers.

    Person::read() is also wrong, isn't it? PersonInfo.txt has all the information inside of it:
    Code:
    Hillary Clinton F 1947 10 26
    Donald Trump M 1946 06 14
    Bernie Sanders M 1941 09 08
    Barack Obama M 1961 08 04
    Melania Trump F 1970 04 26
    Michelle Obama F 1964 01 17
    Yet inside read() you have this line:
    Code:
    in.open (firstName.c.str())
    There is no "Obama" file to open, for example, with his information inside.

    I think you were supposed to read the file line by line and stop when you found a line matching that person's name.

    Finally, about all of this:
    Code:
    bool Person::find (std::string a && std::string f)
    {
        {
            for (int i=0;i< fname.size();i++)
            {
                if (a==firstName[i])
                {
                    f = info[i]
                    return true;
                }
            }
            return false;
                     
    }
     
     
    void Person::printPerson () const
    {
        for (i=0;i<firstName.size();i++)
        {
            std::cout << firstName[i] << "\t";
            std::cout << line[i] << "\n";
        }
    }
    Is there a reason you are doing all of this processing. You can compare a string directly with comparison operators like ==, !=, and <. You can also print a string without any work:
    Code:
    std::cout << line << '\n';
    Don't write code that you don't need to write.

    HTH

  3. #3
    Registered User
    Join Date
    Oct 2016
    Posts
    2
    Thank you whiteflags,

    I appreciate all the help. I am a bit confused.

    I have a couple of questions through out the code. I will try to ask them. Please help answer the ones possible.

    My first concern is that is my person.cpp file correct? or does it seem like it is missing functions? If its missing anything, I want to work on adding those.

    Code:
    #ifndef PERSON_H_INCLUDED
    #define PERSON_H_INCLUDED
    #include <string>
    
    //The code below was provided during the lab.
    
    class Person
    {
        public:
            Person();
            Person(std::string fname, std::string lname , std::string s, int byear, int bmth, int bday );
            std::string findName (std::string lname) const;
            void setName (std::string fname, std::string lname);
            void setSex (std::string s);
            void setBirthInfo ( int byear, int bmth, int bday);
            void read (std::string lname);
            void printPerson () const;
            bool find (std::string a, std::string f) const;
            //void setAge( int age );
            //int getAge() const;
            //void print() const;
    
        private:
            std::string firstName;
            std::string lastName;
            std::string sex;
            int birthYear;
            int birthMonth;
            int birthDay;
            
    };
    Question 2:
    Would I declare name in serveral functions?
    Such as Person::Person
    Person::SetName
    Person::sex
    Person::setbirthAge

    such as below

    Code:
    Person::Person()
    {
        firstName = "";
        lastName = "";
        sex = "";
        birthYear = 0;
        birthMonth = 0;
        birthYear = 0;
    }
    
    Person::Person(std::string fname, std::string lname , string s, int byear, int bmth, int bday)
    {
        firstName = fname;
        lastName = lname;
        sex = s;
        birthYear = byear;
        birthMonth = bmth;
        birthDay = bday;
    }
    
    void std::string Person::setName() const
    {
        firstName = fname;
        lastName = lname;
    }
    
    void std::string Person::setSex()
    {
        sex = s;
    }
    
    void Person::setBirthInfo()
    {
        birthYear = byear;
        birthMonth = bmth;
        birthDay = bday;
    }
    Because here it seems like I am doing the same thing over and over. So if you can explain that please.
    I really dont understand it at the moment.

    Question 3

    Where should i declare line and how? I want to be able to just output line and expect the program to know what to print.
    But im not sure about declaring line.

    Question 4

    What exactly is wrong with these functions? It keeps giving an error that c is not declared.
    I also am not able to get the program to run the .txt file successfully.
    So what should I fix in teh codes below:

    Code:
    void Person::read(string lname)
    {
        ifstream in;
        string line;
        bool more = true;
        in.open (firstName.c.str());
        while (more)
        {
            std::in >> w;
            if(in.fail())
            more = false;
        else
        {
            lname.push_back(w);
            getline (in, line);
            line.push_back(line);
        }
    }
    in.close();
            
    }
    
    bool Person::find (std::string a && std::string f)
    {
        {
            for (int i=0;i< fname.size();i++)
            {
                if (a==firstName[i])
                {
                    f = info[i]
                    return true;
                }
            }
            return false;
                    
    }
    Question 5

    Could you please explain arc and argv? I know they work somewhat like pointers to my understanding but im not sure how?

    Question 5:

    I am trying to declare objects in the main function after I print out the menu. But i am having some trouble getting started. What do you suggest I should start with?

    I was trying to declare them as an array. But im not sure What it shoudl look like?

    Code:
     Function[]
    {
    string fname;
    string lname;
    string sex;
    int byear;
    int bmth;
    int bday;
    }
    But im not sure how I can make it run in the main function and then call it. Would i need a for function or something similar?
    Please explain

    Thank you

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    My first concern is that is my person.cpp file correct? or does it seem like it is missing functions?
    You can answer this question by compiling. If you write a function Person::whatever and it isn't in the class declaration, the compiler will print an error. If you forget to write a function inside of the class declaration, the compiler will also print an error.

    Would I declare name in serveral functions?
    Yes, the code you showed below this question would need to follow this syntax: return-type the name of the class :: the name of the function ( parameter-list )

    The idea is that if you write functions outside of the class definition, like you would to separate code into cpp and hpp files, then the Person:: identifies the function as part of the class.

    Where should i declare line and how? I want to be able to just output line and expect the program to know what to print.
    Print the members of the class instead of line. I really don't think line is what you want to print. Line is a variable local to the read function, and the value of line would change a lot over time.

    What exactly is wrong with these functions? It keeps giving an error that c is not declared.
    Yeah I think you meant to call std::string's c_str() method there. The period is basically an unfortunate typo.

    It's going to be very hard to read the file if you keep trying to use the firstName variable, though. Like I said before, that isn't going to open a file at all; there isn't a file that you can open with that name. The file you want to open is in argv[1], the first argument.

    Could you please explain arc and argv? I know they work somewhat like pointers to my understanding but im not sure how?
    argv is an array of strings containing the command line arguments, and argc is an integer whose value is the length of argv. You will need to use this information to open your file.

    What do you suggest I should start with?
    Try thinking about the program from a bird's eye perspective and achieving small but important goals:

    I think you're supposed to read the file line by line.
    On each line is a different person, so you have to read the information in such a way to make a person.
    Once you make a person, you have to push_back() it to the vector.
    When you have read the whole file, you can use the vector in main to do the rest of the program. It's literally a matter of finding the right person in the vector and then displaying that information.

    HTH

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Also posted here, here and here.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-15-2014, 04:31 AM
  2. how to read info from text file?
    By mike112358 in forum C Programming
    Replies: 13
    Last Post: 01-09-2014, 12:07 PM
  3. Homework: Read and Print to file - Am I oversimplifying?
    By Cameron Taylor in forum C Programming
    Replies: 8
    Last Post: 07-15-2013, 10:41 PM
  4. Replies: 3
    Last Post: 03-13-2013, 07:10 PM
  5. Read struct-like file/print to stdout (again)
    By inakappeh in forum C Programming
    Replies: 3
    Last Post: 09-18-2001, 04:33 AM

Tags for this Thread