避免在C++中读取文件中的标点符号



我正在用c++查找文件中最长的单词。我有解决方案,但代码也考虑了标点符号,我不知道如何避免这种情况。

这就是函数";get_the_langest_word((":

string get_the_longest_word(const string &file_name){
int max=0;
string s,longest_word;
ifstream inputFile(file_name);
if(inputFile.is_open())
{
while(inputFile>>s)
{
if(s.length()>max)
{
max=s.length();
s.swap(longest_word);
}
}
inputFile.close();
}else
cout<<"Error while opening the file!!n";
return longest_word;}

提前感谢的帮助

在c++中,我们早就有了一个很好的方法来指定组成单词的字符模式。std::regex。它很容易使用,而且用途广泛。

一个由1个或多个字母组成的单词可以简单地定义为w+。不需要更多了。如果你想要其他模式,那么这也很容易创建。

对于像您这样的程序,正则表达式也没有复杂性开销或运行时问题。所以,应该使用它。

此外,我们有一个非常好的迭代器,使用它我们可以在std::string中迭代这些模式。std::sregex_token_iterator。这让生活变得非常简单。这样,我们就可以使用C++提供的许多有用的算法。

例如std::maxelement,它采用2个迭代器,然后返回给定范围内的最大元素。这正是我们所需要的。

然后整个程序可以归结为几个简单的语句。

请参阅:

#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <regex>
#include <algorithm>
const std::regex re{ "\w+" };
std::string getLongestWord(const std::string& fileName) {
std::string result{};
// Open the file and check, if it could be opened
if (std::ifstream ifs{ fileName }; ifs) {
// Read complete file into a string. Use range constructor of string
std::string text(std::istreambuf_iterator<char>(ifs), {});
// Get the longest word
result = *std::max_element(std::sregex_token_iterator(text.begin(), text.end(), re), {}, [](const std::string& s1, const std::string& s2) {return s1.size() < s2.size(); });
} // Error, file could not be opened
else std::cerr << "n*** Error. Could not open file '" << fileName << "'nn";

return result;
}
int main() {
std::cout << getLongestWord("text.txt") << 'n';
}

相关内容

最新更新