Need help looping through a text file

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
string word; // The word entered by the user
string result; // The word read from the file
int counter = 0; // Counts the number of lines read from the file
bool found = false; // If the user's word has been found
ifstream inFile; // The input file
int sum = 0;
int n = 0;

///////////////////////////////////
// Start of your code

//open the dictionary file.
inFile.open("dictionary_mac.txt");



//ask the user to input the word they want to search for.
cout << "Enter a word to search in the dicitonary: ";
cin >> word;



// Use a while loop to loop through the file.
inFile >> result;
while (inFile)
{
cout << "Word found in line " << sum << endl;
counter++;
sum += counter;
inFile >> counter;
found = true;
break;
}

if (!inFile)
{
cout << "The word was not found" << endl;
return 1;
}



// If the word is not found display a message.




// End of your code
///////////////////////////////////


system("pause");
return 0;
}
If you need the line number you need to use std::getline and string.find
This part of the code has problems:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    // Use a while loop to loop through the file.
    inFile >> result;
    while (inFile)
    {
        cout << "Word found in line " << sum << endl;
        counter++;
        sum += counter;
        inFile >> counter;
        found = true;
        break;
    }

    if (!inFile)
    {
        cout << "The word was not found" << endl;
        return 1;
    }


The easy part first. This:
1
2
3
4
5
    if (!inFile)
    {
        cout << "The word was not found" << endl;
        return 1;
    }

should be
1
2
3
4
5
    if (!found )
    {
        cout << "The word was not found" << endl;
        return 1;
    }


So there's a clue there. You need to compare the user-supplied input word with that read from the file, result. If they match, set found to true. You know how to test if one string is equal to another?

Your loop reads only one word from the file:
 
   inFile >> result;


In order to read all of the words from the file, place the read operation inside the loop condition:
1
2
3
4
5
6
7
    // Read ALL words from file
    while (inFile >> result)
    {
        // here compare result with word
        // to see whether they are the same.
        // etc.
    }

Topic archived. No new replies allowed.