Reputation: 469
I am writing a program where I read a text file using getline()
and store each line in a vector<string>
.
ifstream flirfile(flir_time_dir);
vector<string> flir_times;
string flir_line;
while (getline(flirfile, flir_line))
{
flir_times.push_back(flir_line);
}
This is the text file that the program reads:
The program works fine but what I want to do is ignore everything on each line except for the hex string in the middle. So in other words ignore everything before the first underscore and after the second underscore (including the underscores). Is there an easy way to do that? And is it better to ignore the text while the file is being read or afterwards when the lines are stored in the vector? Thanks.
Upvotes: 1
Views: 1435
Reputation: 6024
If your compiler supports C++11 you can use regular expression:
#include <regex>
// ...
std::regex my_regex("_[^_]*_");
while (getline(flirfile, flir_line))
{
std::smatch my_match;
if (std::regex_search(flir_line, my_match, my_regex))
flir_times.push_back(my_match[0]);
}
Upvotes: 3
Reputation: 409176
There are ways to split strings on separators, which means you can split the string on the '_'
character, and use only the middle-part.
A simple way of doing this is to use std::getline
and std::istringstream
:
while (getline(flirfile, flir_line))
{
std::istringstream is{flir_line};
std::string dummy;
std::string flir;
std::getline(is, dummy, '_');
std::getline(is, flir, '_');
flir_times.push_back(flir);
}
Upvotes: 4