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

Thread: file input

  1. #1
    Join Date
    Mar 2002
    Posts
    55

    file input

    Hi, I want to read some data from a file for example something like this:

    3 // number of variables
    var1 = 40
    var2 = 50
    var3 = 70

    I only want to read the value of the vars and write them to an array in my program, but I can't find out how to read the data as integers and not as characters

    Any hint or sample app as it should be easy for the professional would be nice

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    you can use standard C++ iostream ....

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
    	vector<int> array;
    
    	ifstream infile("test.txt");	// open input file (it is close automatically)
    
    	if (infile)						// if opened OK
    	{
    		int i,j,n;
    
    		infile >> n;				// read in number of integers
    		if (infile.fail())
    		{
    			cout << "error reading number of integers" << endl;
    			return 1;
    		}
    
    		for (i=0; i<n; i++)
    		{
    			infile >> j;			// read in next integer
    			if (infile.fail())
    			{
    				cout << "error reading integers" << endl;
    				cout << "read in successfully " << array.size() << " integers" << endl;
    				return 1;
    			}
    			array.push_back(j);		//   store in the array
    		}
    
    		cout << "values read in ... " << endl;
    		for (i=0; i<array.size(); ++i)
    		{
    			cout << array[i] << endl;
    		}
    	}
    	else
    	{
    		cout << "unable to open input file " << endl;
    		return 1;
    	}
    
    	return 0;
    }

  3. #3
    Join Date
    Mar 2002
    Posts
    55

    Thumbs up

    thx

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured