You have 2 choices, maybe more but at least 2.
Get the string the user wants when they run the command, my favorite.
Or get the string after the program stats(Has limits in my opinion).
To get the string from the user when they run the command, I created a file named SearchFileForString.cpp.
I start main with
int main(int argc, char* argv[])
For my code I created 3 search patterns
1 2 3
|
char *s0 = argv[0]; // Command
char *s1 = argv[1]; // Search String
char *s2 = argv[2]; // File to Search
|
You do not really need s0 or argv[0] because that is just the command you ran such as SearchFileForString.
For my program I made argv[1] the string and argv[2] the filename so it's not hard coded, in other words you can use it for any file and any string.
Then I created a while loop to get line
getline(InputFile,line);
and a check to see if the string was found
1 2 3 4 5 6
|
if ((offset = line.find(argv[1], 0)) != string::npos)
{
// If match found, Do this
}
else
{// do nothing}
|
This is a great program to write for beginners because you will learn a lot and once you have this working, you can modify it to do most anything with a file and string.
Line count, word count, char count, number count
single or double string searches
output to another file
sort contents
the list goes on and on.