gpt4 book ai didi

c++ - 如何从 txt 文件 c++ 中提取括号之间的数字?

转载 作者:行者123 更新时间:2023-11-28 04:35:06 26 4
gpt4 key购买 nike

我的问题是:我的逻辑有问题。我已经检测到它何时有括号,但现在我需要找到数字并知道它们在 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.

结果应该是:year : 2008 - 2 times, year : 2010 - 2 times, etc.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;
}

最佳答案

您可以使用 std::regex_search匹配线的方法。但记得包括 #include <regex>在文件的顶部。

#include <regex>
#include <iostream>
#include <fstream>
#include <map>


int main()
{
std::ifstream readStream("path/to/your/Example.txt");
std::map<int, int> countMap; // Map containing (year, count) value pairs.
std::string in;
std::regex reg(R"(\([a-zA-Z\s]*,?\s*([0-9]+)\))"); // For the regex: \([a-zA-Z\s]*,?\s*([0-9]+)\)

while (std::getline(readStream, in)) {
std::match_results < std::string::const_iterator > m;
if (std::regex_search(in, m, reg)) { // If the current line matches our regex pattern.
int year = std::stoi(m[1]); // The second element of the array contains our string representing the year.

auto val = countMap.find(year);
if (val != countMap.end()) { // If the year is already in the countMap we want to increment it.
countMap[val->first] = val->second + 1;
} else {
countMap[year] = 1; // year doesn't exist in the countMap, it is the first time.
}
}
}

for (auto x : countMap) { // x is of type std::pair<int, int> which is our (year, count) value pair
std::cout << "year " << x.first << " is - " << x.second << " times." << std::endl;
}

return 0;
}

关于c++ - 如何从 txt 文件 c++ 中提取括号之间的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51691603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com