【发布时间】:2018-08-05 05:19:58
【问题描述】:
我的问题是:我的逻辑有些问题。我已经检测到它何时有括号,但现在我需要找到数字并知道它们在 txt 文件中重复了多少次。这是我的txt文件:
(Visual basic)
(Llorente)
(Porto, 2008)
(Sommerville, 2010)
References
Visual Basic. (s.f.). Navarra.
Llorente, P.B. (s.f.). Fortran.
Porto, J.P. (2008)
Sommerville, I. (2010). Software Engineering. Unite Kingdom: Pearson.
结果应该是:年份:2008 - 2 次,年份:2010 - 2 次,等等。 PD:谢谢,我很菜鸟。
#include <regex>
#include <iostream>
#include <fstream>
#include <map>
//33
int main()
{
std::ifstream readStream("references.txt");
std::map<int, int> cMap;
std::string input;
std::regex reg(R"(\([a-zA-Z\s]*,?\s*([0-9]+)\))");
std::regex inte("(\\+|-)?[[:digit:]]+");
///333
while (std::getline(readStream, input)) {
std::match_results < std::string::const_iterator > m;
if ((std::regex_search(input, m, reg)) ) {
int year = std::stoi(m[1]);
auto value = cMap.find(year);
if (value != cMap.end()) {
cMap[value->first] = value->second + 1;
} else {
cMap[year] = 1;
}
}
}
//33
for (auto x : cMap) {
std::cout << "year " << x.first << " is - " << x.second << " times." << std::endl;
}
//3
return 0;
}
【问题讨论】:
-
对于regex 来说,这听起来像是一份完美的工作(就像首先找到括号一样)
-
我使用 g++ 我不能使用正则表达式。
-
嗯? g++ 支持正则表达式,它们是 C++ 的一部分。
-
@john “我遇到了一个问题,我选择了正则表达式来解决它。现在,我遇到了两个问题。” ;-)
-
要在字符串中查找数字,您可以遍历字符
c直到找到数字 (c >= '0' && c <= '9')。然后,只要找到数字,就进行迭代。或者,更简单:使用strtol()。 (它也会告诉你停止字符的数字和指针。)
标签: c++ file-io extract ifstream