Search code examples
c++c++17readfile

Reading in one word from a file


I'm new to C++, and I need to find the one word inputted (searchWord) within the text file "input.txt".

I have it now where it will output every word in the file, but I need it to just output the inputted string and find it.

#include<iomanip>
#include<fstream>
#include<string>
using namespace std;

int main(){
    // Variable Declaration
    string fileName;
    string searchWord;
    int exitValue = 0;

    // Name the file to open
    ifstream inputFile;

    // Prompt the user to enter the file name
    cout << "Enter the name of the file: ";
    cin >> fileName;

    // Logic to determine if the file name equals "input.txt"
    if (fileName == "input.txt"){ // if user input = input.txt
        inputFile.open("input.txt"); // opening input.txt
    }
    else{
        cout << "\nCould not open '" << fileName << "'." << endl;
        exit(0);
    }

    // Prompt the user for a word to search for in the file
    cout << "Enter a value to search for: ";
    cin >> searchWord;

    // Logic to determine if the inputted string is in the file or not
    while (inputFile >> searchWord){
        cout << "\n'" << searchWord << "' was found in '" 
            << fileName << "'." << endl;
    }

    inputFile.close();
    return 0;
}

Solution

  • Do it just a bit different:

    // Logic to determine if the inputted string is in the file or not
    string inputWord;
    while (inputFile >> inputWord){ // Do not overwrite the given searchWord
        if(inputWord == searchWord ) { // Check if the input read equals searchWord     
            cout << "\n'" << searchWord << "' was found in '" 
                 << fileName << "'." << endl;
            break; // End the loop
        }
    }