int main()
{
int number_of_words = 0;
int prevnum = -1;
string previous = "";
string current;
while (cin >> current)
{
++number_of_words;
if (previous == current)
{
cout << "word number: " << number_of_words << "\n"
<< "Repeated Word: " << current << "\n";
previous = current;
}
else while (prevnum == number_of_words)
{
number_of_words = 0;
prevnum = 0;
break;
}
}
}
在这个应用程序中,我试图在文本中显示重复的单词及其位置编号。当它完成运行输入的语句时,它会保留number_of_words
以进行下一个输入。我尝试使用else while
条件修复此问题,while循环将中断。
我应该做些什么? while循环在中断后是否会再次运行,或者我是否需要将其置于另一个while循环中,提示用户是否已准备好输入某些文本?
*这是Ch。 3所以我猜我应该继续前进,但很好奇
答案 0 :(得分:0)
试试这个:
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int number_of_words;
string previous;
string current, input;
while (true)
{
previous = "";
number_of_words = 0;
cout << "\nWrite the data\n";
getline(std::cin, input);
stringstream ss;
ss << input;
while (ss >> current)
{
++number_of_words;
if (previous == current)
cout << "word number: " << number_of_words << "\n"
<< "Repeated Word: " << current << "\n";
previous = current;
}
}
}
我使用了一个stringstream变量来打破每个输入循环,所以我可以重置计数器。