gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:23:21 24 4
gpt4 key购买 nike

我目前正在尝试计算文件中的单词数。在此之后,我打算让它计算文件中两个单词之间的单词数。例如。我的文件可能包含。 “你好,我叫詹姆斯”。我想数一下字数,所以是 5。然后我想数一下“Hello”和“James”之间的字数,所以答案是 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" , 使用 find()来自 <algorithm>标题让迭代器到达他们的位置:

// 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");

如果它们不在 vector 中,find()将返回 words.end() ;出于说明的目的忽略错误检查,您可以通过计算它们之间的差异来计算它们之间的单词数,并针对包含 "Hello" 进行调整。在范围内:

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

您可以使用 operator-()这里是因为std::vector::iterator是一个“随机访问迭代器”。更一般地说,您可以使用 std::distance()来自 <iterator> :

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

这样做的好处是可以更好地描述您的实际工作。另外,为了将来引用,这种代码:

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

可以简化为:

bool f() {
return x;
}

x已经转换为 bool对于 if .

关于C++计算文件中两个单词之间的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13403284/

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