read string from the file
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: read string from the file

  1. #1
    Join Date
    Apr 2012
    Location
    Slovenia
    Posts
    115

    read string from the file

    I have an example text file that contains:

    ***xyz text********
    ***********<td>temperatura: </td><td class="data">19.8 &deg;C</td>
    ***xyz text********
    ***********

    How can i extract the number 19.8 from that file?

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,316

    Re: read string from the file

    One approach is to use a HTML parser. Another approach is to use a regular expression. Depending on the data, for all we know you could just search for " &deg;C" then extract the text just before it.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,556

    Re: read string from the file

    One way using the class string could be
    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    
    const string fname = "tdata.txt";
    
    int main()
    {
    ifstream ifs(fname.c_str());
    
    	if (!ifs.is_open()) {
    		cout << "cannot open input file " << fname << endl;
    		return 1;
    	}
    
    string line;
    
    	while (getline(ifs, line)) {
    		size_t deg = line.find("&deg");
    		size_t st = (deg != string::npos) ? line.rfind(">", deg) : string::npos;
    
    		if (deg != string::npos && st != string::npos)
    			cout << line.substr(st = line.find_first_not_of(" ", st + 1), line.find_last_not_of(" ", deg - 1) - st + 1) << endl;
    
    	}
    	return 0;
    }
    For the given text, this will display 19.8
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  4. #4
    Join Date
    Apr 2012
    Location
    Slovenia
    Posts
    115

    Re: read string from the file

    thanx for the code.

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center