Searching text file with prefix

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
    ifstream inFile("F:\\test.txt");

    string check = "M";
    string line;

    if (inFile)
    {
        while(getline(inFile, line))
        {
            stringstream stream(line);
            string firstWord;
            stream>>firstWord;
            if(firstWord == check)
            {
                string name, place;
                static const auto delimiter = '/';
                getline(stream, name, delimiter)&&getline(stream, place);
                cout<<check<<name<<","<<place<<"\n";
            }
        }
    }
}

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
Last edited on
Read the entire file line-by-line. If the line starts with the prefix, print it.

Alternatively, just build a regular expression and run it over your input.

This is strictly what you're asking for, in the style of a Unix filter program, but grep does the same job better.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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;
  }

  auto const 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";
  }
}
Last edited on
Topic archived. No new replies allowed.