136,498 views
17 votes
17 votes
A program to search words in c++

User Personman
by
2.6k points

1 Answer

19 votes
19 votes

Answer:

a starting point might be after you get this working, you can allow them to enter more words and iterate your search,

for each argument (not counting the first one that is the file name)

search for the word, show the lines...

and more files too, for that matter, for each file, for all the words... (at this point you MUST put flags on what each thing is, up to now, you can use the order of args)

just note that arg[] are c-strings. you can assign a string a c-string, so promotion lets you do things more normally, or you can process it as-is depending on what you use it for (see how I just used it in the file name but moved it to a string in the target?). I plan to use target a lot, but the file name only in one statement ever, no need to upcast it.

Step-by-step explanation:

int main(int argc, char* argv[])

{

if(argc < 3) //if the user did not provide enough command line inputs.

//you can, and should probably, do more exhaustive input validation and maybe have them

//do flags as well rather than rely on the order of the arguments to be correct.

{

cout << "usage: mygrep filename word"

return 1;

}

ifstream infile(argv[1]); //attempt to open the first target as the file

string target = argv[2]; //assign target from the second argument

...

User Masterov
by
3.2k points