You are here:

C++/strlen, .substr

Advertisement


Question
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"
#include<iostream>
#include<fstream>
#include<string>

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 );        
infile.close();
while ( (y[z++] =infiles.get() ) != EOF );
infiles.close();
 for(b=1;b<=L1;b++)
  for(z=1;z<=L2;z++)
   { if((a.substr(b,10))==(y.substr(z,10)))         
     { cout<<b<<a.substr(b,10)<<"  ";
       cout<<z<<y.substr(z,10)<<"\n";          
     }
   }
return 0;
}


Answer
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 : princeatapi@yahoo.co.in

Thanks and Regards !
Prince M. Premnath  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

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

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.