-3

i tried many methods but i still confused. i replace "word" by a char and string var. i put the word from x in another var but it failed. what is wrong with this code ?

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    char x[99];
    fstream file;
    file.open("data.txt",ios::in);
    for (int i=1 ; !file.eof() ; i++) {
        file.getline(x,99,' ');
        if(x=="word")
            cout << "found";}
    file.close();
    return 0;
}
  • 1
    Possible duplicate of [Comparing two strings in C?](https://stackoverflow.com/questions/14232990/comparing-two-strings-in-c) – user202729 Mar 28 '18 at 08:12
  • 3
    In this particular case, you should stop using `char[]` and use `std::string` instead. – user202729 Mar 28 '18 at 08:13
  • ... because the char buffer could be shorter than a line in a file; `std::string` extends automatically, if necessary. Otherwise, you would have to consider cases such as `"wo"` being at the end of the buffer and `"rd"` coming with next read. – Aconcagua Mar 28 '18 at 08:30
  • 2
    Read about [misuse of `eof()`](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Mar 28 '18 at 08:31

1 Answers1

0

First of all using a character array is not a good idea use string.h instead and use the builtin OOP functions to process text in a file. it will be more easier

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

    int main()
    {
        cout  << "Write the path of the file\n" ;
        string path ;
        cin >> path ;

        ifstream file(path.c_str()) ;

        if(file.is_open()) //checking if files exists  
        {
            cout << "Write the word you're searching for\n" ;
            string word ;
            cin >> word ;

            int countwords = 0 ;
            string candidate ;
            while( file >> candidate ) // for each candidate word read from the file 
            {
                if( word == candidate ) ++countwords ;
            }

            cout << "The word '" << word << "' has been found " << countwords << " times.\n" ;
            return 0;
        }
        else
        {
            cout << "Error! File not found!\n" ;
            return 1 ;
        }
    }
Zain Ul Abidin
  • 940
  • 7
  • 17