Thread: Reading Data From A File - Error

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    7

    Unhappy Reading Data From A File - SOLVED

    many thnx to MacGyver & Daved...

    Problem: i have a data file (*.txt or *.dat), N rows and 3 columns of data. Don't know the N number!
    i want to read all the data from the file and see if the data are read properly.


    SOLUTION
    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <conio.h>
    using namespace std;
    
    int main()
    {
        vector<double> vList;
        double data;
        fstream file;
        file.open("data.txt",  fstream::in | fstream::out);
            
        while(file>>data)
            vList.push_back(data);
    
        
        cout<<"Row Tot:"<< vList.size();
        cout<<"\nX"<<"\tY"<<"\tZ"<<endl;  
        
        for(int i=0; i< vList.size()/3.; i++)   // 3. : for 3 columns...
        {
            for(int j=0; j<3; j++)
                 cout<< vList[(i*3)+j]<< " ";
    	cout<<endl;	
        }
        getch();
    }
    Last edited by ~Stingray~; 05-18-2007 at 02:35 PM.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Why are you using fstream::binary?

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    7
    i was trying everything
    i took a look at;
    Code:
    http://www.cplusplus.com/reference/iostream/fstream/
    but couldn't figure it out

  4. #4

  5. #5
    Registered User
    Join Date
    May 2007
    Posts
    7
    thnx for the link but no good

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    OK, so what is it that you're trying to do? If you don't tell us what your end goal is other than just to store data, we can't guess your intentions, especially since your syntax for declaring arrays was off the mark, and you said you don't know what you're doing with files.

    I'm guessing you want us to write some code. Here's a really bad way to read from a file like yours and store the items sequentially in a vector:

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    int main(int argc, char *argv[])
    {
    	bool bLoop = true;
    	unsigned int i,j;
    	int iRet = 0;
    	double d;
    	std::vector<double> vList;
    	std::ifstream *input;
    	
    	if(argc < 2)
    	{
    		std::cerr << "Usage: " << argv[0] << " <file>" << std::endl;
    		return 1;
    	}
    	
    	input = new std::ifstream(argv[1],std::ifstream::in);
    	if(input->is_open())
    	{
    		do
    		{
    			*input >> d;
    			if(input->good())
    			{
    				vList.push_back(d);
    			}
    			else bLoop = false;
    		}while(bLoop);
    		for(i=0;i<vList.size()/3;i++)
    		{
    			for(j=0;j<3;j++)
    			{
    				std::cout << vList[(i*3)+j] << " ";
    			}
    			std::cout << std::endl;
    		}
    	}
    	else
    	{
    		std::cout << "File could not be opened." << std::endl;
    		iRet = 2;
    	}
    	
    	delete input;
    	return iRet;
    }
    Last edited by MacGyver; 05-18-2007 at 03:58 AM.

  7. #7
    Registered User
    Join Date
    May 2007
    Posts
    7
    edited my first post...

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Well it's no wonder this doesn't work very well:
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        int i;
        double X[i],Y[i],Z[i];  
        fstream file;
        file.open("data.txt");
        for(i=0; i<=15; i++)
          file >> X[i] >> Y[i] >> Z[i];
    
        cout<<"\nX"<<"\tY"<<"\tZ"<<endl;
    
        for (int i=0; i<=15;i++ )   
            cout<<X[i]<<"\t"<<Y[i]<<"\t"<<Z[i]<<endl;
        system("pause");
    }
    It's actually a wonder it even compiles. You declare X, Y, and Z to be variable-sized arrays, holding an undefined number of elements, because the variable i has not been initialized.

    You should also call file.close() when you're done with the file, and stop using system("pause") if possible, or if not include <cstdlib> . . . see the FAQ.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You could switch your arrays to be pointers and "new" data for them and deal with the memory explicitly by resizing it if you run out, but that gets messy. Another alternative is to use vectors instead of arrays, which is probably preferred.

  10. #10
    Registered User
    Join Date
    May 2007
    Posts
    7
    many thanks MacGyver & dwks, great tips.

    i didn't know much about vectors, checked out for a few tips.
    your code was very vey helpful MacGyver

    just a tiny problem left, the last vector is 0.
    it doesn't contain a value...

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <conio.h>
    using namespace std;
    
    int main()
    {
        bool Loop = true;
        vector<double> vList;
        double data;
        fstream file;
        file.open("data.txt");
        
        do
        {
            file >> data;
            if(file.good())
                vList.push_back(data);
            else 
                Loop = false;
        } 
        while(Loop);
        
        cout<<"\nX"<<"\tY"<<"\tZ"<<endl;  
        for(int i=0; i<=vList.size()/3; i++)
        {
    		for(int j=0; j<3; j++)
    		       cout<< vList[(i*3)+j]<< " ";
    		cout<<endl;	
        }
        getch();
    }

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    So changing to < fixed that problem?

    BTW,
    Code:
        do
        {
            file >> data;
            if(file.good())
                vList.push_back(data);
            else 
                Loop = false;
        } 
        while(Loop);
    could be changed to:
    Code:
        while (file >> data)
        {
            vList.push_back(data);
        }

  12. #12
    Registered User
    Join Date
    May 2007
    Posts
    7
    maybe a little silly, i had to edit my txt file.
    i had to drop the cursor to a empty line and save it. (before it was at the end of the data)

    Code:
    before
    1 2 4
    2 4 3|
    Code:
    after
    1 2 4
    2 4 3
    |

    Code:
     while (file >> data)
        {
            vList.push_back(data);
        }
    works great thnx
    Last edited by ~Stingray~; 05-18-2007 at 12:36 PM.

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    I think making the change to while (file >> data) would allow it to work with either version of the text file. Calling file.good() returns false if there was a failure or if eof was reached. In your original input file, the 3 is the last character, so on the last read 3 is read into data and the eofbit is set. The call to good() returns false and so the 3 is never pushed on to the vector. With my code, the operator>> returns !fail(), so if the read succeeds it will allow the object to be pushed back, even if the eof is reached at the same time.

  14. #14
    Registered User
    Join Date
    May 2007
    Posts
    7
    definetly works
    it's intresting about good() returning false at the last data.

    thanks daved and MacGyver for all of your help. finally a worknig nice script...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  4. Stupid compiler errors
    By ChrisEacrett in forum C++ Programming
    Replies: 9
    Last Post: 11-30-2003, 05:44 PM
  5. Linking error
    By DockyD in forum C++ Programming
    Replies: 10
    Last Post: 01-20-2003, 05:27 AM