Hi folks,

I'm having problems with my loops, and possibly more...hehe!

I'm loading a text file, which has 1 word per line, into a buffer and I want to search the buffer for all the words that start with the same prefix (3 letters) and return the words in an edit box.

I successfully accomplished reading 1 line, compare the prefix, and show the word in an edit box if prefix matches. Now, I'm just stuck with making it loop.

Exemple:
The Prefix is: "Bla".
The text file contains:
Benji
Bennett
Bentley
Beverly
Billy
Birch Grove
Birch Hill
Birch
Birchdale
Birchmount
Birchwood
Black Beach
Black
Blair
Bleury
Blue Heron
Blue Rock

The program will return:
Black Beach
Black
Blair


Here's the code for the button:

#include <iostream>
#include <fstream>
#include <strstream>

//....

void Csn3Dlg::OnBnClickedButton1()
{
   UpdateData(TRUE);

   FILE * pFile;
   char buffer [20];
   CString prefix = "Old";
   CString readprefix;
   CString temp;
   CString read;
   int count=0;   

   pFile = fopen ("d:\\namelist.txt" , "r");

  if (pFile == NULL)
   {
   MessageBox("Error opening file", NULL, MB_OK | MB_ICONSTOP);
   exit(0);
   }
   
   else
   {
     while ( ! feof (pFile) )
     {
       fgets (buffer , 20 , pFile);
       fputs (buffer , stdout);
	   read = read+buffer+"\r\n";  
     }
	  fclose (pFile);
	
//My problems are in there:
	 while ( prefix != readprefix )
	 {
	   for (int j = count ; read[j]!='\n'; j++)
	   temp = temp+read[j];
	   for(int i=0 ; i!=3 ; i++)
	   readprefix = readprefix+temp[i];	
	
	    if(prefix == readprefix)
	    break;
	    else
	    count++;
	 }

	 m_out = temp;
    
   }
	
	UpdateData(FALSE);
}

Any suggestions or help will be much appreciated!

line 29 is wrong

while( fgets (buffer , 20 , pFile) )
{
   // blabla
}

fgets() normally adds the '\n' that is in the file at the end of the input string that you need to strip off. And it would make your life a lot easier if you would put the strings in an array instead of concantinating them into one big string.

while( fgets (buffer , sizeof(buffer) , pFile) )
{
   if( buffer[strlen(buffer)-1] == '\n')
       buffer[strlen(buffer)-1] = 0;       
   // blabla
}
Be a part of the DaniWeb community

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