简体   繁体   中英

c++ Searching for occurrences from file and return line number

I hope that someone could point me to the right direction for this program. The main problem is the searchstring function. The program:

The function searchString has two parameters that are the file object passed in by reference and a search string.

The function reads a line at a time and searches for an occurrence of the search string. Each time the search string is found, it writes out the line of the occurrence in the output. Also the function returns the number of lines where the search string occured.

This is my "info.txt" file.

hello there, what is your name?

how can i help you?

welcome to his domain!

Edit

The program works now. Does anyone know how to search for uppercase letters?

Here is what I have so far:

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

using namespace std;

int searchString(fstream &, string);
int main()
{
    string filename;
    string look;
    fstream infile;
    cout<<"Enter file: ";
    cin>>filename;
    infile.open(filename.c_str(), ios::in);
    if(!infile)
    {
        cout<<filename<<" couldn't open."<<endl;
        return 1;
    }

    cout<<"What do you want to search in the text file? ";
    cin>>look;
    cout<<"Beginning to search for "<<look<<endl;
    cout<<look<<" was found in "<<searchString(infile, look)<<" lines."<<endl;

    infile.close();
    return 0;
    }

int searchString(fstream &infile, string see)
{
    string input;
    int count=0;
    int number=0;
    while(getline(infile,input))
    {
        number++;
        cout<<"Line "<<number<<": "<<input<<endl;
        if(input.find(see,0)!=string::npos)
        {
            cout<<"found "<<see<<" in line "<<number<<endl;
            count++;
        }
    else
    {
        cout<<see<<" is not found."<<endl;
    }
}
return count;
}

I guess your problem is how can you find a substring inside a string, right? If your problem is how to read files too check this >Link< .

For every line you read from your file you just need to do this:

 String toFind = "example";
 String needle = " " + toFind + " ";
 if (s1.find(needle) != std::string::npos) {
  count++;
  cout << _line + ": Just found another line with the word" << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM