-2
#include <iostream>
#include <fstream>
//#include <cstring>
//#include <string>

using namespace std;

int main()
{
    string word;
    ifstream infile;
    infile.open ("inputfile.txt"); 

    if (infile.fail()) 
        { 
            cout<<"UNABLE TO ACCESS INPUT FILE";
        }

    while(!infile.eof())
        {
            while (infile>> word)
                 {
                    cout<<word<<endl<<endl;
                 }  
        }

    infile.close ();

    system("pause");

    return 0;   
}

The above code couts all the words in the input text file. How do I cout just one word of my choice? I am asking this because I want to eventually be able to cin a word from user, and find that word in the input file either to delete or replace it with another word.

  • you can use an if statement to check what the word it before printing it – Gab Mar 08 '17 at 06:32
  • 2
    First please read [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Then think about what you're doing in the innermost loop (the outer isn't needed, and is wrong as you now have read). – Some programmer dude Mar 08 '17 at 06:32

1 Answers1

1

here is example to find word from string

std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");

 std::size_t found = str.find(str2);
 if (found!=std::string::npos)
 std::cout << "first 'needle' found at: " << found << '\n';
Sweta Parmar
  • 269
  • 1
  • 11