C++ 计算文件中两个单词之间的单词

C++ Counting words in a file between two words

本文关键字:单词 两个 之间 计算 文件 C++      更新时间:2023-10-16

我目前正在尝试计算文件中的单词数。在此之后,我计划让它计算文件中两个单词之间的单词。例如。我的文件可能包含。"你好,我叫詹姆斯"。我想数字,所以5。然后我想数一数"你好"和"詹姆斯"之间的字数,所以答案是 3。我在完成这两项任务时遇到麻烦。 主要是由于不确定如何构建我的代码。 这里的任何帮助将不胜感激。我目前使用的代码是使用空格来计算单词。

这是我的代码:

读字.cpp

string ReadWords::getNextWord()
{
bool pWord = false;
char c;
while((c = wordfile.get()) !=EOF)
{
if (!(isspace(c)))
{
nextword.append(1, c);
}
return nextword;
}
}
bool ReadWords::isNextWord()
{
if(!wordfile.eof())
{
return true;
}
else
{
return false;
}
}

主.cpp

main()
{
int count = 0;
ReadWords rw("hamlet.txt");
while(rw.isNextWord()){
rw.getNextWord();
count++;
}
cout << count;
rw.close();
}

它目前所做的是计算字符数。我敢肯定这只是一个简单的修复和我错过的愚蠢的东西。但是我已经尝试了足够长的时间去寻找一些帮助。

任何帮助都非常感谢。 :)

无需逐个字符解析文件,只需使用istream::operator<<()即可读取空格分隔的单词。<<返回流,当仍可从中读取流时,流的计算结果为true作为bool

vector<string> words;
string word;
while (wordfile >> word)
words.push_back(word);

使用<iterator><algorithm>实用程序有一个常见的公式,它更详细,但可以与其他迭代器算法组合:

istream_iterator<string> input(wordfile), end;
copy(input, end, back_inserter(words));

然后你有单词的数量,可以随心所欲地处理它们:

words.size()

如果要查找"Hello""James",请使用<algorithm>标头中的find()将迭代器置于其位置:

// Find "Hello" anywhere in 'words'.
const auto hello = find(words.begin(), words.end(), "Hello");
// Find "James" anywhere after 'hello' in 'words'.
const auto james = find(hello, words.end(), "James");

如果它们不在向量中,find()将返回words.end();为了说明目的,忽略错误检查,您可以通过取它们之间的差异来计算它们之间的单词数,调整范围中包含"Hello"

const auto count = james - (hello + 1);

您可以在此处使用operator-()std::vector::iterator因为它是"随机访问迭代器"。更一般地说,您可以使用<iterator>中的std::distance()

const auto count = distance(hello, james) - 1;

这样做的好处是可以更好地描述您实际在做什么。另外,为了将来参考,这种代码:

bool f() {
if (x) {
return true;
} else {
return false;
}
}

可以简化为:

bool f() {
return x;
}

由于x已经转换为ifbool.

要计数:

std::ifstream infile("hamlet.txt");
std::size_t count = 0;
for (std::string word; infile >> word; ++count) { }

仅在开始和停止之间计数:

std::ifstream infile("hamlet.txt");
std::size_t count = 0;
bool active = false;
for (std::string word; infile >> word; )
{
if (!active && word == "Hello") { active = true; }
if (!active) continue;
if (word == "James") break;
++count;
}

我认为"return nextword;"应该是"else return nextword";"否则你每次都从函数getNextWord返回,无论字符是什么。

string ReadWords::getNextWord()
{
bool pWord = false;
char c;
while((c = wordfile.get()) !=EOF)
{
if (!(isspace(c)))
{
nextword.append(1, c);
}
else return nextword;//only returns on a space
}
}

要计算所有单词:

std::ifstream f("hamlet.txt");
std::cout << std::distance (std::istream_iterator<std::string>(f),
std::istream_iterator<std::string>()) << 'n';

要在两个单词之间计数:

std::ifstream f("hamlet.txt");
std::istream_iterator<std::string> it(f), end;
int count = 0;
while (std::find(it, end, "Hello") != end)
while (++it != end && *it != "James")
++count;
std::cout << count;

试试这个: 线下

nextword.append(1, c);

continue;