You are here:

C++/strlen, .substr


i am trying 2 extract 2 diff paragrafs, that i read n from 2 diff notepad txt files and put into 2 diff arrays, and then compare them 2 print a report of matching words, using a length factor of 10, i am a new C++ college student and i can't quite figure out y my solution isnt working, my is code below, any advice would b greatly appreciated, thank u!

#include "stdafx.h"

using namespace std;

int main()          
{static char a[500];
static char y[500];
int b,z,L1=391,L2=437;
const char* filename="c:\\project3intext1.txt";
const char* filenames="c:\\project3intext2.txt";
ifstream infile(filename);
ifstream infiles(filenames);
if (!infile) cout<<"no input file\n";
if (!infiles) cout<<"no input file\n";
while ( (a[b++] =infile.get() ) != EOF );        
while ( (y[z++] =infiles.get() ) != EOF );
   { if((a.substr(b,10))==(y.substr(z,10)))         
     { cout<<b<<a.substr(b,10)<<"  ";
return 0;

Hi dear Joe !

I found few issues with your coding !

1. Initialize the array indexes b , z to 0 ; Since by default it will contain a garbage value and hence for each pass possibly the array index might go beyond the range !

2. Usage of substr() should be reviewed again , since it may be a member function the class string  and not for a simple character  array data structure !

Presenting you a simple C++ code to understand the usage of substr member function

int main()          
  string str="We think in generalities, but we live in details.";
  string str2, str3;
  size_t pos;

  str2 = str.substr (12,12); // "generalities"

  pos = str.find("live");    // position of "live" in str
  str3 = str.substr (pos);   // get from "live" to the end

  cout << str2 << ' ' << str3 << endl;
 return 0;

If you use string class to manipulate the contents of the file then you have to alter the programme in such a way , else you have to use the function strstr() , it will work fine on char arrays !

For more assistance :

Thanks and Regards !
Prince M. Premnath  


All Answers

Answers by Expert:

Ask Experts


Prince M. Premnath


Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)


More than 5 years


©2016 All rights reserved.