ThePeskyWabbit
ThePeskyWabbit

Reputation: 427

cin in a while-loop

#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:

  1. 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.

  2. 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

Answers (3)

ppp
ppp

Reputation: 1

If you want to use string, you must use #include string or std_lib_facilities.h

Upvotes: -1

John Zwinck
John Zwinck

Reputation: 249093

  1. The default behavior is to stop on whitespace when reading strings as you are doing. You can change it to read whitespace by saying std::cin >> std::noskipws.
  2. The previous word is always assigned at the end of the loop. Given the answer to part 1, it should be clear why previous works.

Upvotes: 2

Aleph
Aleph

Reputation: 1219

  1. If you use 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).
  2. You assign current to previous: 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

Related Questions