I have a text file with a name/place on each line. Is there a simple way of searching the text file based on a prefix entered by user and printing every line that starts with that prefix.
Tested with sample file:
Mr John Smith/ London
Ms Jane Doe/ New York
Mlle Ella Corine/ Montreal
Madam Sophia Seymour/ Melbourne
Mrs Margaret Spencer/ Cape Town
M Pierre Rabeau/ Lyon
# include <algorithm>
# include <fstream>
# include <iomanip>
# include <iostream>
# include <string>
# include <cerrno>
# include <cstring>
int main (int argc, char **argv) {
/* 2 args only. */
if (argc != 2) {
std::cerr << "usage: " << *argv << " prefix\n";
return 1;
}
autoconst prefix = std::string{argv[1]};
/* Get the file contents. */
for (auto line = std::string{}; std::getline(std::cin, line); )
if (line.substr(0, prefix.size()) == prefix) std::cout << line << "\n";
/* Did we fail before reaching the EOF? */
if (std::cin.rdstate() & compl std::ios::eofbit) {
std::cerr << "error reading from stdin: " << std::strerror(errno) << "\n";
}
}