Reading a File
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: Reading a File

  1. #1
    Join Date
    Dec 2009
    Posts
    596

    Reading a File

    Hi guys. In this code I want to change it get the information from a file instead of the keyboard.

    Code:
    int main()
    {
    	vector<bowarrowcmb> bowandwt;
    	bowarrowcmb record;
    	streamsize prec = cout.precision();
    		
    	cout << "Enter a bow weight followed by a series of arrow weights: \n\n";
    	while (read(cin, record)) {
    		bowandwt.push_back(record);
    	}
    
    	typedef vector<bowarrowcmb>::size_type vec_sz;
    	vec_sz size = bowandwt.size();
    
    	if (size == 0)
    		throw domain_error("Empty vector");
    
    
    	system("CLS");
    	for(vector<bowarrowcmb>::size_type i = 0;
    		i != bowandwt.size(); ++i) {
    		cout << bowandwt[i].bowt;
    		for( int j = 0; j != bowandwt[i].arwt.size(); ++j){
    			cout << " " << setprecision(4) << gpi(bowandwt[i].arwt[j],bowandwt[i].bowt);
    		}
    		cout << endl;
    	}
    	setprecision(prec);
    
    	system("pause");
    
    	return 0;
    }
    I think that what i need to do is to load the contents of the file line by line into bowandwt. I don't know how to do that. Can some please point me in the right direction how to do that? I've looked at file read snippets on the internet but don't know how to modify What I've seen for what I need. The following code that I copied from a website sums integers and works and is what I'm basing my learning from.
    Code:
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    using namespace std;
    
    int main() {
        int sum = 0;
        int x;
        ifstream inFile;
        
    	inFile.open("C:\\Users\\matos\\Documents\\TxtDocs\\test.txt");
        if (!inFile) {
            cout << "Unable to open file";
            exit(1); // terminate with error
        }
        
        while (inFile >> x) {
            sum = sum + x;
        }
        
        inFile.close();
        cout << "Sum = " << sum << endl; 
    
    	system("pause");
    
        return 0;
    }

  2. #2
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Reading a File

    How is the data serialised to the file?

    Generally you should add a pair of functions to your class interface. I call them read and write taking a basic_istream<...> and a basic_ostream<...> reference respectively( you can simply use an istream& and an ostream& if templating the stream type isn't important). Then write non-member, nonfriend versions of operators << and >> which kick down to read and write in your class interface.

    With those in place, writing your structs to and from a file is as easy as pie.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  3. #3
    Join Date
    Dec 2009
    Posts
    596

    Re: Reading a File

    As far as how the file is serialized: I'll just type a few lines of data from notepad without a deliminator. Then when I get that to work I'll try to get a CSV file to work. I don't know if that answers the serialized question though. As far as writing non-member, nonfriend versions of operators << and >>: That's not in me yet. What topic is that to look up and get aqainted with? Is it operator overloading? Sounds too much for me yet and I might need to work my way up to that.

  4. #4
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Reading a File

    Heres a very basic example. untested but should work.
    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    class Test
    {
        private:
            int num1;
            int num2;
            int num3;
    
        public:
            Test( int n1, int n2, int n3 )
                : num1( n1 ), num2( n2 ), num3( n3 )
            {}
    
            ostream& Write( ostream& os ) const
            {
                os << num1 << '/' << num2 << '/' << num3 << endl;
                return os;
            }
    
            istream& Read( istream& is )
            {
                char sep;
                is >> num1 >> sep >> num2 >> sep >> num3;
                return is;
            }
    };
    
    ostream& operator <<( ostream& os, const Test& test )
    {
        return test.Write( os );
    }
    
    istream& operator >>( istream& is, Test& test )
    {
        return test.Read( is );
    }
    
    int main()
    {
        Test test1( 1, 2, 3 );
        Test test2( 4, 5, 6 );
        ofstream ofile( "Test.txt" );
        ofile << test1 << test2;
        ofile.close();
        cout << test1 << test2 << endl;
        ifstream ifile( "Test.txt" );
        ifile >> test2 >> test1;
        ifile.close();
        cout << test1 << test2 << endl;
        return 0;
    }
    Last edited by Russco; March 31st, 2011 at 03:15 PM.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  5. #5
    Join Date
    Dec 2009
    Posts
    596

    Smile Re: Reading a File

    Thank you very much for the help Russco. It works great and looks like I'll be able to use this for my learning project and it's also a nice lesson on class usage. I'll let you know how it goes when I get my little app to use this new class. Once again Thanks a million.

    -Juan

  6. #6
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Reading a File

    Read and Write must mirror each other. Write sets the file format, Read must be able to read the same format. This class test now knows how to write itself to an ostream and read from an istream. The nonmember operators are called in for instance...

    cout << test1;

    This calls operator << ( cout, test1) which calls test1.Write( cout ) which places each member into the stream separated by in this example the '/' char and a newline at the end of each test written. I should have used '\n' instead of endl as endl causes a stream flush but the point was to show you how to structure simple serialisation of classes.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  7. #7
    Join Date
    Dec 2009
    Posts
    596

    Re: Reading a File

    Ok. I'll change it to '\n'. This is great. Once I get done with helping my son with his homework I''ll try to undertand this program thouroughly before using it.

  8. #8
    Join Date
    Dec 2009
    Posts
    596

    Re: Reading a File

    Quick question: So that I know better how to talk the talk; how would I answer the question "How is the file serialize?"( Given the file is serialize the way you did it.).

  9. #9
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Reading a File

    Generally with classes you have two options. Write the whole class to a stream with ostream::write and read in with istream::read which is a very brittle way of doing it. To ensure this works properly the code that does the reading has to be written on the same compiler with the same compiler settings etc. as the code which does the writing as the compiler is free to add padding members. The other way is how I have shown you. That is to write each member in turn into a file and read each in in turn too. This way will work properly in all cases as long as the reading function can read from the format written by the writing function.
    This class is very simple. it just writes 3 ints with separators and reads them in reading and ignoring the separators.
    Serialization is the process of writing an object to a data store in such a way as it can be deserialized to reconstitute an object identical to the one written. I was basically asking what format the file was in so we knew how to create the function that does the reading.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center