I have problem in count substring from a file that have sequence of string.After i run the code, the result should be bigger than 1 but the code still show the same result which is 1 every time i run the code.I don't know where are wrong. Any help is very appreciated.

#include <iostream>
#include <string>
#include <fstream>
#include <conio.h>
using namespace std;
 
int main()
{
	//ifstream file;
	ifstream fin;
	string filename;
    string s, substring;
    int count = 0; // Count variable to count the number of matches within the file.
    //file.open("DATA1.txt"); // Opens the file cities.txt.
 
    string t1 = "ttt";
	//cout << "Enter all or part of a city name: ";
	//getline(cin,city); // User-inputted city name.
	//substring = t1;
 
    do {
    cout << "Enter input data file name:";
    cin >> filename;     // Get the file name.
    fin.open(filename.c_str());  // Convert to C-string and open it.
    if (!fin) {          // Will fail if didn't exist.
        cout << "Unable to open " << filename << endl;
    }
    } while (!fin);          // Continue until good file.

	while (getline(fin,s)) // Read a line. If successful, enter the loop.
    {
         //bigstring = s;
         if (s.find(t1) != -1)
         {
         //cout << s << endl;
         }
        count++;
    }
 
    cout << "There were " << count
        << " matches in the file" << endl;
 
	getch();
	return 0;
}

Contains of the file are like this:
gatcctccatatacaacggtatctccacctcaggtttagatctcaacaacggaaccattgccgacatgagacagttaggtatcgtcgagagttacaagctaaaacgagcagtagtcagctctgcatctgaagccgctgaagttctactaagggtggataacatcatccgtgcaagaccaagaaccgccaatagacaacatatgtaacatatttaggatatacctcgaaaataataaaccgccacactgtcattattataattagaaacagaacgcaaaaattatccactatataattcaaagacgcgaaaaaaaaagaacaacgcgtcatagaacttttggcaattcgcgtcacaaataaattttggcaacttatgtttcctcttcgagcagtactcgagccctgtctcaagaatgtaataatacccatcgtaggtatggttaaagatagcatctccacaacctcaaagctccttgccgagagtcgccctcctttgtcgagtaattttcacttttcatatgagaacttattttcttattctttactctcacatcctgtagtgattgacactgcaacagccaccatcactagaagaacagaacaattacttaatagaaaaattatatcttcctcgaaacgatttcctgcttccaacatctacgtatatcaagaagcattcacttaccatgacacagcttcagatttcattattgctgacagctactatatcactactccat

std::string.find() does not return an integer -- it returns an unsigned integer. So checking for -1 will not work. It should be checked against std::string::npos.

if( s.find(t1) != string::npos)
{

}
This article has been dead for over six months. Start a new discussion instead.