Write the function: int searchForTwoStrings(char *filename, char *s1, char *s2);
ID: 3688729 • Letter: W
Question
Write the function:
int searchForTwoStrings(char *filename, char *s1, char *s2);
It returns the line number of the first line in the file filename that contains both s1 and s2 (with case ignored).
The first line in the file is line number 1.
It returns 0 if there is no line that contains both of these strings and returns -1 and sets errno if it cannot read the file or another error occurs.
Lines are delimited by the newline character, ' '.
Do not assume that the entire file will fit in memory, but you may assume a maximum length of a line in the file of 10K.
Return -1 if a line is found that is too long before the strings are found.
The readline function from the restart library may be of use here.
Explanation / Answer
Hi I have implemented required function. You can use in your program, pass required data.
int searchForTwoStrings(char *filename, char *s1, char *s2){
ifstream fileInput;
string line;
unsigned int curLine = 0;
// open file to search
fileInput.open(filename);
if(fileInput.is_open()) {
while(getline(fileInput, line)) { // I changed this, see below
curLine++;
if ((line.find(s1, 0) != string::npos) && (line.find(s2, 0) != string::npos)) {
cout << "found: " << s1 << " and "<<s2<< " line: " << curLine << endl;
}
}
fileInput.close();
}
else cout << "Unable to open file.";
return curLine;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.