Strings using For loops

Hello,
I have an assignment that asks for input from the user call it "search". Then using a for loop, keep getting input from the users until the words match. Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string a, b;
	cout << "Enter a search word: ";
	getline(cin,b); 
	cout << "Searching for the word [" << b << "] ... "; 
	for (int x = 0; x != b ; x++) // why does this not work
	{
		getline(cin,a);
		cout << "[" << a << "]";
	}
	cout << "Found! There were " << a << " words between occurrences of " << b << "."; // Display how many words were entered until the "word" word was found.
}
b has the type std::string while x has the type int. You may not compare them with each other.
I would change the loop the following way

1
2
3
4
5
6
7
8
9
int count = 0;
do
{
   getlaine( cin, a );
   count++;
} while ( a != b );


cout << "Found! There were " << --count << " words between occurrences of " << b << "."; 
Last edited on
A do while loop would be great but I have to use a for loop. Do you have any tips on how to write the program with a For loop? And the For loop has to loop until the first input is repeated. How do I determine what that value should be?(if that makes sense).
Last edited on
1
2
3
4
5
6
7
8
9
10
11
int main()
{
    string  a,  b;
    cin >> b;
    int count;
    for(count = 0; a != b; count++) getline(cin, a);

    cout << "Found! There were " << count << " words between occurrences of " << b << ".";

	return 0;
}
Topic archived. No new replies allowed.