检测重复的单词 C++,不检测第一个单词
detect repeated word c++, doesn't detect the first word
这是我正在练习的一些代码,来自编程:使用C++的原理和实践:
#include <iostream>
using namespace std;
int main() {
int numberOfWords = 0;
string previous = " "; // the operator >> skips white space
string current;
cout << "Type some stuff.";
cin >> current;
while (cin >> current) {
++numberOfWords; // increase word count
if (previous == current)
cout << "word number " << numberOfWords
<< " repeated: " << current << 'n';
previous = current;
}
}
它按预期工作,但我注意到它没有检测到重复的第一个单词——例如"run run"将没有返回,"run run run"会告诉我我重复了单词编号2,但没有单词编号1。出于好奇,如果单词1重复,我需要在这个代码中更改什么来检测?
这样你就跳过了第一个单词:
cin >> current;
while (cin >> current) {
编辑:由于第一个单词不能与任何东西进行比较,我们可以将第一个单词的值设置为前一个单词,并从第二个单词开始比较:
cin >> previous;
while (cin >> current) {
只需编写您想要的代码。有一种方法:
#include <iostream>
using namespace std;
int main()
{
int numberOfWords = 1;
bool previousMatch = false;
string previous; // the operator >> skips white space
string current;
cout << "Type some stuff." << std::endl;
cin >> previous;
while (cin >> current)
{
if (previous == current)
{
if (! previousMatch)
{ // Previous word repeated too
cout << "word number " << numberOfWords
<< " repeated: " << current << 'n';
previousMatch = true;
}
cout << "word number " << numberOfWords + 1
<< " repeated: " << current << 'n';
}
else
previousMatch = false;
++numberOfWords; // increase word count
previous = current;
}
}
相关文章:
- 文本文件中的单词链表
- 使用CMake检测支持的C++标准
- 在指针的帮助下,文本文件中单词的频率
- 当套接字连接断开时检测C/C++Unix
- C/C++预处理器是否可以检测一些编译器选项
- WMI检测进程创建事件-c++
- 如何根据单词在文本中出现的概率输出单词
- 基于树莓pi的tensorflow lite量化ssd目标检测
- 下面是我为检测链接列表中的循环而制作的代码
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 落砂模拟碰撞检测C++和SFML
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- 为什么C++编译器没有检测到正确声明的类?
- C++-字符串是否包含一个带有简单循环的单词
- 检测重复的单词 C++,不检测第一个单词
- C++ — 使用 getch() 进行箭头键检测会莫名其妙地打印一些单词