This function does not search for words.
It takes as input a file name and a line number. It tries to find and read that line.
The output starts with a line stating: "The result from (fileName
), line #lineNumber
: "
It is followed by a text indented by a tab and followed by the found line contents. This second line of output is left incomplete (not followed by a newline).
The found contents is empty, if the file has has less than the requested number of lines or if any of the lines before the requested line has more than 999 characters.
If the requested line has more than 999 characters it is truncated to 999 characters.
Other questions:
1) infile
is a function-scope object of automatic storage duration and type std::basic_ifstream<char, std::char_traits<char>>
, which is initialized for reading from the file named in fileName
.
2) The member function c_str() built into the standard library string class returns a pointer to the string contents as a non-modifiable, nul-terminated character array, which is the format typically used in C for strings (type const char *
). For historical reasons the file-based standard library streams take their file name arguments in this format.
3) Humans typically count line numbers starting with one. That is the convention used for the lineNumber
parameter. The algorithm used must match this. The currentlineno
local variable is used to mean 'the number of the next line to be read'. As such it must be initialized with 1
. (This is somewhat confusing, considering the name of the variable.) Other implementations that initialize the line counter with 0 are possible - and indeed natural to most C++ programmers.
4) See any textbook or online reference of C++. Look for "pre-increment" (++x
) and "post-increment" (x++
) operators. They have the same side effect (increment x), but differ in the value of the expression. If you don't use the result they are equivalent (for basic types).
C++ programmers usually prefer pre-increment as it can generally be implemented more efficiently for user-defined types.
5) Even more basic textbook question. a < b
tests for a less-than relationship, a != b
tests for inequality.
Note: All answers assume that the types used are from the standard C++ library, i.e that appropriate includes of the <string>
and <iostream>
headers and necessary using
directives or declarations are used.