Hi everyone,

Im trying to solve this question:

write a C++ program to find a given word in a file. It should display all the line numbers where the word occurs.

this is the code that i did so far, the problem is it wont display all the right line number, it only displays "1" :( I hope that you guys can help me fix it up.

#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int main()
{
string s1;
ifstream in ("file.txt");
int lines = 0;
cout << "Enter your search string: " <<endl;
cin >> s1;
in.seekg(0,ios::beg);
lines ++;
cout<<"The  string occured at lines: " << lines<<endl;
in.close();
getch();
return 0;
}

Thanks in advance,
itchap

Recommended Answers

All 4 Replies

i am new to eriting c codes and in one of the programming i am currently doing, i came across something like #ifdef_cplusplus. i don't know what it means. help

i am new to eriting c codes and in one of the programming i am currently doing, i came across something like #ifdef_cplusplus. i don't know what it means. help

You should ask this question in a new thread, so others dont get confused on which of us to help.

in.seekg(0,ios::beg);
lines ++;

You should put this in a loop, now it will find 1 occurence and continue with the rest of your code.
so something like:

While (not the end of the file)
{
    look for searchstring
    lines++;
    if string is found
    {
       cout << "found at line" << lines << endl
    }
}

You should put this in a loop, now it will find 1 occurence and continue with the rest of your code.
so something like:

While (not the end of the file)
{
    look for searchstring
    lines++;
    if string is found
    {
       cout << "found at line" << lines << endl
    }
}

Thanks Nick!!!!!!!!!!!!!!!!!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.