Unable to figure out why assignment not working

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
  string first("t");
  string second;
  while (cin>>second);
  {
  if (second==first) cout<<"repeated";
  
  }
}


I expect that if I input t, the program will give output "repeated". Anything other than t, and the program will assign the entered value to first.

In other words, if I repeat two words, I should get the output "repeated". However, this is not happening. Help will be appreciated.
while (cin>>second);
is exactly same as
1
2
3
while (cin>>second)
{
}

Your loop repeats one statement and that statement has only the semicolon.
Make sure that if you are using the string data type, you type the preprocessor directive:
#include <string>
That should fix some of the issues.
If you want the program to repeat anything put twice besides t, you must have first equal second after the output as so:
1
2
3
4
5
while (cin >> second)
	{
		if (second == first) cout << "repeated" << endl;
		first = second;
	}

I also recommend using endl so that after "repeated" is output, the next input will be asked for on the next line.
Last edited on
@keskiverto Thanks, the problem is addressed by removing semicolon. @AlexNewport02 Thanks for the tip.
Topic archived. No new replies allowed.