Reputation: 427
#include <iostream>
using namespace std;
int main()
{
string previous;
string current;
while (cin >> current)
{
if(current == previous)
{
cout << "repeated word";
}
previous=current;
}
return 0;
}
my questions are:
When it states while(cin>>current)
, why is the entire entered string of text not assigned to current? I don't understand how it compares all the words individually.
How does it get a word for previous. How does it know 2 of the same words are adjacent?
EDIT: I think I just understood why. Tell me if I am wrong but I think its because the compiler stops the cin
assignment at the space and that first word is assigned to current, then it compares it to the previous word, but since it is the first word, it does not have a previous word so it just assigned the first word to previous and compares the next word in the sentence until there are no more words left. I'm fairly certain this is how it works but I am going to leave this up in case anyone is ever wondering something similar.
Upvotes: 1
Views: 1596
Reputation: 1
If you want to use string, you must use #include string
or std_lib_facilities.h
Upvotes: -1
Reputation: 249093
std::cin >> std::noskipws
.Upvotes: 2
Reputation: 1219
std::istream::operator>>
with a std::string argument, it reads characters until it finds any whitespace character. This means that it will only read a single "word" if you're entering a sentence. Use std::getline(cin, current);
to read an entire line (until a newline character).previous = current
. This means that after reading current
, you make previous
current
. So the next time, before you read, you can compare previous with current to see if they're the same thing.Upvotes: 1