if (!getline(cin, search)) {
count;
}
If getline fails, you basically do nothing here. You're reading the value of count (0) and doing nothing with it.
{ ifstream in("MarkScheme.txt");
if (!in){
cerr<<"Mark Scheme not found"<<endl;
return EXIT_FAILURE;
}
} // End local
This also does practically nothing. Because the definition of in is inside braces, it's local to that block. When you get to the "End local" comment, it's destroyed. I can imagine that you wanted to use in for later input, but had to change it to cin because the compiler said in didn't exist.
I have no idea what you want your code to do, so I can't give you an improved version.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
A naive implementation would look something like this:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line;
cout<<"Enter a file to open: ";
getline ( cin, line );
ifstream in ( line.c_str() );
if ( in ) {
int count = 0;
while ( getline ( in, line ) ) {
ifstream markstream ( "MarkScheme.txt" );
string mark;
while ( getline ( markstream, mark ) ) {
if ( mark == line )
++count;
}
}
cout<<"The total count is "<< count <<endl;
}
}
A better implementation would look more like this:
#include <fstream>
#include <iostream>
#include <set>
#include <string>
using namespace std;
set<string> load_file ( const string& filename )
{
ifstream in ( filename.c_str() );
if ( !in )
return set<string>();
string line;
set<string> ret;
while ( getline ( in, line ) )
ret.insert ( line );
return ret;
}
int main()
{
string filename;
cout<<"Enter a file to open: ";
getline ( cin, filename );
set<string> user = load_file ( filename );
set<string> mark = load_file ( "MarkScheme.txt" );
int count = 0;
for ( set<string>::const_iterator it = user.begin(); it != user.end(); ++it ) {
if ( mark.find ( *it ) != mark.end() )
++count;
}
cout<<"The total count is "<< count <<endl;
}
And there would be degrees of improvement as you went away from the manual version to an even more abstracted version. ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>I have tried both recommended programs
Both recommended programs were suggestions to get you started. Naturally, you would need to modify them to suit your needs. For example, if you wanted to do a substring search then comparison with == will most likely not do what you want. In that case you would probably use the find member function of the string class:
if ( mark.find ( line ) != string::npos )
++count;
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401