You are here:

C++/Pulling information from a file

Advertisement


Question
Hello, I am using the compiler Bloodshed Dev C++ and I am wondering how I would extract a line from a file for use in an IF statement. I am pretty new at C++ but am learning it on my own time from tutorials on the net and so far I have found nothing in regards to extracting information in the manner I am wanting. I wish to have an IF statement look at the file, say "Ok, if the word KEY is in the file, go to this function or sub (in VB they were called functions or classes), and if it is not in the file go to this function or sub" I am just getting started on C++ and I love it but I am just a novice right now :P thanks for the help

Answer
Leaving the requirement to be used in an if statement (note: _all_ keywords in C and C++ are _lowercase_) aside for one moment the basic operations that you would have to perform are:

- open the file
- iterate (or enumerate) through this file looking for a the required match (note: define the meaning of match here: exact case e.g. KEY is a match but Key and key are not, only if surrounded by whitespace so KEY is a match but KEYNES is not etc...).
- if found give a true result, otherwise give a false result.

To perform file operations C++ has the C++ IOStreams library. To perform iteration over sequences the C++ standard library has various iterators, including stream iterators. To perform operations on sequences iterated over there are algorithms, including algorithms to find values in a sequence.

The following is an example program (built and tested using MS VC++ 8.0, I do not have Dev C++ installed at present - sorry). It will locate the desired word using whitespace as the word separation characters and exact case matching so "this is the KEY to use" will find "KEY" but "this is MILTON KEYNES", "this is the key to use" and "Key, what KEY?" will not. The file test.dat needs to be in the current directory where the program is executed from - so you may have to do a bit of trial and error to find which directory is current when run from within the Dev C++ IDE.

       #include <iostream>   // For std::cout , std::cerr
       #include <fstream>    // For std::ifstream
       #include <algorithm>  // For std::find
       #include <iterator>   // For std::istream_iterator
       #include <string>     // For std::string
     
       int main()
       {
         std::ifstream istrm( "test.dat" ); // Create input file
         // stream, opening
         // the file

         if ( istrm.is_open() ) // check file opened OK
         {
         // Create input stream iterator attached to test.dat
         // file stream istrm reading in strings using the
         // stream's operator>> - so each 'word' is a separate
         // item in the sequence.
         std::istream_iterator<std::string>
         istrmIterator( istrm );

         // Create similar iterator to use as end of sequence
         // marker at end of file.
         std::istream_iterator<std::string>
         istrmIteratorEnd;

         // Use the standard find algorithm over the sequence of
         // 'words' from the start of the file to the end of the
         // file to locate the exact 'word' string "KEY" - i.e.
         // only all uppercase "KEY" will match. The find
         // function will return an iterator pointing to the
         // position in the sequence the value was located at or
         // the end of sequence iterator value (istrmIteratorEnd
         // in this case) if the value was not located.
         if (    istrmIteratorEnd
         ==  std::find( istrmIterator
         , istrmIteratorEnd
         , std::string("KEY")
         )
         )
         {
         std::cout << "Did not find KEY in "
         "file\n";
         }
         else
         {
         std::cout << "Found KEY in file\n";
         }
         }
         else
         {
         std::cerr << "ERROR: Could not open file test.dat\n";
         }
       }

You can replace the text output for finding / not find the required value with the calls to the functions you want.

I am not going to explain further - you should however spend time looking into the facilities provided by the standard C++ library and how to use it.

Needless to say this is only one way to achieve what you ask.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

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.

Experience

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 http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.