如何读取特定单词的字符串并计算发现的时间
How to read a string for a specific word and count the times it was found
我当前正在尝试编写一个程序来检查txt文件以查找特定的单词,游骑兵并对其进行计数。一旦计算一切,我就需要将其打印出流浪者的总数和弦的总数。我不知道该怎么做。
我几乎失败了C ,确实需要此帮助。这就是我到目前为止提出的:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
string ranger[50];
ifstream rangerin("Ranger.txt");
if ( !rangerin ) {
cout << "Invalid Filen";
return EXIT_FAILURE;
}
string message;
while ( getline(rangerin, message) ) {
}
}
使用以下策略。
- 循环中的单词读取文件。
- 将您阅读的每个单词与您要寻找的单词进行比较。
- 如果它们相同,请增加计数。
- 完成阅读后,退出循环。
- 打印计数。
int main()
{
int count = 0;
std::ifstream rangerin("Ranger.txt");
if ( !rangerin ) {
cout << "Invalid Filen";
return EXIT_FAILURE;
}
std::string word;
while ( rangerin >> word )
{
// This needs to be modified if case insensitive comparison
// is expected.
if ( word == "ranger" )
{
++count;
}
}
std::cout << "Number of times 'ranger' was found: " << count << std::endl;
return 0;
}
编辑
上述方法的麻烦是,如果您的文件中有ranger,
,则不会计算。这意味着比较必须进行一些完善。
写一个函数 isWordRanger
并在该功能中隐藏详细信息。
bool isWordRanger(string const& word)
{
// Add additional refined checks as needed.
return ( (word == "ranger") ||
(word == "ragner,") ||
(word == "ranger.") );
}
更改main
要使用:
if ( isWordRanger(word) )
{
++count;
}
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度