CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2001
    Posts
    12

    Input from file & FOR loop

    I am a newbie working on a problem that will perform various mathematical functions. My problem is I would like to know how to read in values from a file using FOR loops. I need to read in the number of values followed by the sequence of values. (I've been playing around with this for over a week and just need some help to get the ball rolling.) Thanks in advance!

  2. #2
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    Could you give an example of what your datafile looks like.
    Succinct is verbose for terse

  3. #3
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    Roughly (may be problems, but here's an idea)

    Code:
    #include <fstream>
    using namespace std;
    
    void processFile(string filename)
    {
         ifstream f(filename);
    
         vector<double> values;
    
         int count;
         f >> count;
         for( int i = 0; i < count; ++i )
         {
              double val;
              f >> val;
              values.push_back(val);
         }
    }
    Jeff

  4. #4
    Join Date
    Jun 2002
    Posts
    224

    Re: Input from file & FOR loop

    Just an idea
    Code:
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
      ifstream is("input");
    
      if ( ! is )
        return 1; // error opening
      
      while ( is.good() )
      {
        int count;
        for ( is >> count; is.good() && count; count-- )
        {
          double d;
          is >> d;
          // do something creative here
        }
        if ( count )
          return 2; // error too few values
      }
    
    	return 0;
    }
    The input file may look like this:
    Code:
    4 1.2 3.4 5.6 6.7
    2
    1.2
    1.3
    Regards,
    ZDF

    What is good is twice as good if it's simple.
    "Make it simple" is a complex task.

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