除了@MM. 的回答,您可以使用<regex>
C++ 11 的新功能。但是请注意,目前并非所有标准库都完全实现了这一点,因此您可能还想在Boost.regex
必要时回退。
#include <fstream>
#include <iostream>
#include <sstream>
// note: Most C++11 regex implementations are not up to scratch, offer
// Boost.regex as an alternative.
#ifdef USE_BOOST_REGEX
#include <boost/regex.hpp>
namespace std
{
using ::boost::regex;
using ::boost::regex_match;
using ::boost::smatch;
}
#else
#include <regex>
#endif
#include <string>
#include <tuple>
#include <vector>
int main()
{
// open input file
std::ifstream in("file.txt");
if (!in.is_open()) return 1;
// ECMAScript syntax!
std::regex empty_or_comment_re("\\s*(?:#.*)?");
// note: only matches integers
std::regex values_re("\\s*(\\S+)\\s+(\\S+)\\s+(-?\\d+)\\s*");
// will contain the results
std::vector<std::tuple<std::string, std::string, int> > results;
size_t lineno = 0; // for error reporting
std::string line;
// read lines
while (getline(in, line))
{
++lineno;
// match empty or comment lines
if (regex_match(line, empty_or_comment_re)) continue;
// match lines containing data
std::smatch match;
if (!regex_match(line, match, values_re))
{
std::cerr<< "ERROR: malformed line in file.txt, line " << lineno
<< ".\n";
return 1;
}
// read integer from match
int n;
std::istringstream iss(match[3]);
iss >> n;
// append to results
results.push_back(std::make_tuple(match[1], match[2], n));
}
}