processRecords()
is a very generic name and doesn't say what is being done. A better name would bedisplayMthLastItem()
(assuming you don't follow Daniel Sokolov's adviceDaniel Sokolov's advice and split the function out further into the find and display operations).Spacing around function arguments is a little inconsistent:
auto splitLoc= record.rfind(" "); // NO SPACE std::string::size_type index = std::stoi( record.substr( splitLoc ) ); // HAS SPACE
index
has typestd::string::size_type
. This is generally only needed when indexing into astd::string
. The problem definition says that it's an integer, so either declare it as anint
or, since you're using C++11, asauto
(which will be deduced toint
as the return type ofstd::stoi
.As presented, the input data set has a blank line; your code will crash because the
string::rfind()
call will returnstring::npos
if it can't find the search string. Add a check for that value:void processRecords( const std::string& record ) { auto splitLoc= record.rfind(" "); if( splitLoc != std::string::npos ) { // ... the rest of the function goes here... } }
Function
readInputFile()
takes its argument by value; change it to a reference-to-const to prevent copies being made of its argument:void readInputFile( const std::string& fileName ) // "string&", not "string"
You don't need to call
std::ifstream::close()
at the end ofreadInputFile()
: the destructor will close the file for you as soon asinfile
goes out of scope when the function returns.