You are here:

C++/input float values from a file


i am creating a program in which i need to read in a text file of floating point values given in somewhat a matrix form.i need to read only the sixth and seventh columns of each line.but the problem is that the no of columns in each row are not exactly same they are sometimes ten at other times i am confused about how to do it.i cannot possibly read them as characters as i need values for further calculations. please suggest me any help if you can.

You state that only the values of the 6th and 7th items of the 10 or 12 on each line are of interest to you.

   [Note: possible ambiguity:
       You say you cannot read values as characters as you need values for further calculations.
       I presume you mean the values of the 6th and 7th items on each line and not the others
       that you state you do not require.
       However maybe you need these other values at some point - in which case why state you do not?
       That is if you do need these other values elsewhere then this is obviously not a concern of
       the problem you are asking about here and other arrangements are made - e.g. re-reading the
       file to extract the other values you require when required.
   -- end note]

Hence the 1st to 5th item and the 8th to 10th or 12th items on each line - are of no interest and can be considered trash. To put it another way for the latter items: all items after the 7th item on each line are of no interest.

You need to be able to read the 1st to 5th values individually so you know when you arrive at the 6th - however you do not care about their value. You do not care about the value or quantity of items following the 7th item , so just read those as a block text following the 7th item up to and including the end of the line.

With these observations in mind we can write an initial scheme to handle it in pseudo code:

       Open file for reading on in
       For Each line in file in:
         Skip 5 floating point values from in
         Floating Point value6
         Floating Point value7
         in >> value6
         in >> value7
         Save values
         Skip to start of next line from in
       End For Each
       Close file stream in

The Skip 5 floating point values from in might be a function that would work something like so:

       SkipFloatingPointValues( InputStream in, Unsigned Integer n )
         String dummy
         For i = 1 to n
         in >> dummy
         End For
       End Function

Of course this is not very C++ other than the way formatted values are read using >> and for the purposes of this example I am, as is often the case with example code, ignoring error checking. It does give you a set of steps that will do what we want - it just has to be translated into C++ viz:

First the header files required; iostream is only really required for the example usage code in main.

       #include <iostream> // for std::cout and std::cerr messages in main
       #include <fstream>  // for std::ifstream
       #include <vector>   // for std::vector
       #include <string>   // for std::string
       #include <utility>  // for std::pair
       #include <limits>   // for std::numeric_limits

Now the SkipFloatingPointValues function, which follows the pseudo code version pretty closely:

       void SkipFloatingPointValues( std::istream & in, unsigned int n )
         std::string dummy;
         for ( unsigned int i = 0; i != n; ++i )
         in >> dummy;

Next for some type aliases that names a vector of pairs of doubles type used to store the 6th and 7th values from each line:

       typedef std::pair<double, double>   PairDouble;
       typedef std::vector<PairDouble>     VectorPairDouble;

And at last the main logic, wrapped in a function that returns a bool value: true if all data read, false otherwise.
Again this follows the pseudo code pretty closely, but with a little extra error checking:

       bool ReadFloatingPointPairsFromFile
       ( VectorPairDouble & values
       , std::string const & filename
         std::ifstream in(filename.c_str() ); // open file for reading on in

         while ( in ) // for each line in file in, unless some error occurs
         SkipFloatingPointValues( in, 5 );

         double value6(0.0);
         double value7(0.0);

         in >> value6;
         in >> value7;

         // Save values. (only if stream state OK)
         if ( in )
         values.push_back( std::make_pair(value6, value7) );
         // Skip to start of next line from in
         in.ignore( std::numeric_limits<int>::max(), '\n' );        
         // We return true if we are at the end of file, false otherwise
         // On return the in stream object is destroyed causing the file
         // to be closed
         return in.eof();

Note that we pass in a VectorPairDouble by reference to be filled with read values and the filename of the data file to read the values from.

ReadFloatingPointPairsFromFile can be used like so:

   int main()
       VectorPairDouble  theValues;
       if ( ReadFloatingPointPairsFromFile(theValues, "test.dat") )
         std::cout << "Read " << theValues.size() << " pairs of values:\n";
         for ( unsigned int i=0; i<theValues.size(); ++i )
         std::cout << "\t("  << theValues[i].first
         << ", "   << theValues[i].second
         << ")\n";
         std::cerr << "Error: Call to ReadFloatingPointPairsFromFile failed."
         << std::endl;
       return 0;   

Where the file test.dat contains data like so (less the leading white space on each line):

       1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1
       1.2 2.2 3.2 4.2 5.2 6.2 7.2 8.2 9.2 10.2 11.2 12.2
       1.3 2.3 3.3 4.3 5.3 6.3 7.3 8.3 9.3 10.3
       1.4 2.4 3.4 4.4 5.4 6.4 7.4 8.4 9.4 10.4
       1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.5 12.5
       1.6 2.6 3.6 4.6 5.6 6.6 7.6 8.6 9.6 10.6 11.6 12.6

The output if all is OK should be as follows:

       Read 6 pairs of values:
         (6.1, 7.1)
         (6.2, 7.2)
         (6.3, 7.3)
         (6.4, 7.4)
         (6.5, 7.5)
         (6.6, 7.6)

As you have not given any indication of the delimiters used in your file between items I have assumed the C++ std::istream default of white space. You should also probably ensure the final line terminates in a newline - although I think this would only really be a problem if you required extraction of the last item on the line for the last item on the last line in the file.

The code was tested using the data shown above in a file called test.dat (in a suitable directory) on my MS Windows Vista machine built using MS Visual C++ 2005 and under Ubuntu Linux 8.0.4 built using g++ 4.2.3. I remind you that this is only _example_ code and so is not of production quality - in particular some error states may not be handled as well as could be.

Hope this is of use. If the possible ambiguity I mentioned meant I did not grasp your meaning then please clarify what you require with a follow up question.  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at


©2017 All rights reserved.