hmmm...
let me explain the above code:
take input the value you want to search.
get value
equivalent code is:
1 2
|
cout << "Enter a numerical value to see if it exists in that file: ";
cin >> value;
|
value is integer
convert the "value" to string because string cant find integers
it can only find string's. to convert value to string we can do this:
equivalent code is:
1 2
|
std::ostringstream oss; //for this include sstream
oss << value;
|
oss is a string class when you do: oss << value it will convert value to a string
i.e. lets say value is '10' it will convert it to its equivalent string "10".
i have done this so that we can find 10 in the input file.
loop untill you didnt find eof
code is:
while(!number_file.eof())
now what you will do:
you extract one line from the input stream and find 10 in this line like this:
get a line from the file like this:
code:
::getline(number_file, strLine);
what this will do is, it will get you a single line from stream number_file.
so if the file is like this:
Classes for 10 elementary 10 geometric
shapes like LineShape 10 and
PolygonShape 10 are rather easy
to 10 implement,
it will get you:
"Classes for 10 elementary 10 geometric"
correct??
now what we have to do is find "10" in this input.
we have the line in the variable: strLine
we do strLine.find(what to find, position to start)
it will return the position of the found string or else npos if the string is not found.
i have put this in a while loop so that it will keep on finding 10 in a line till it didnt get a npos which mean there is no 10 left in the line.
code:
1 2 3
|
int pos_to_start = 0;
while((pos_to_start = strLine.find(oss.str(), ++pos_to_start)) != std::string::npos) // keep finding the value till we didnt get npos
count++; //if found increment the count
|
now in the first pas pos_to_start is 0
oss.str() will give 10 as we converted value to string in line 8 & 9.
pos_to_start is 0
so it will find 10 in the line:
"Classes for 10 elementary 10 geometric" at pos 12.
and we increment count.
now the value of pos_to_start is 12, next time it will start the operation from position 13 in the same line:
"Classes for 10 elementary 10 geometric"
and find 10 at pos 26 and value of pos_to_start will be 26. count will be 2
but now it wont find a 10 in the string and the loop will break.
we empty the current line this way:
strLine = "";
the code will reach at the start of the while loop and read the next line:
"shapes like LineShape 10 and"
the same thing will happen. the loop continues till it didnt find the eof.
now you can print the count.
hope it will help you in understanding the code.