-
September 23rd, 2014, 12:24 PM
#1
read string from the file
I have an example text file that contains:
***xyz text********
***********<td>temperatura: </td><td class="data">19.8 °C</td>
***xyz text********
***********
How can i extract the number 19.8 from that file?
-
September 23rd, 2014, 12:27 PM
#2
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 " °C" then extract the text just before it.
-
September 23rd, 2014, 02:47 PM
#3
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("°");
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. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
September 23rd, 2014, 03:25 PM
#4
Re: read string from the file
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|