Help! I'm not satisfied with this code fragment.

My goal is to read a set of lines from a file and print out the lines containing a "keyword" along with their line number. I've managed to do so, but I'm unsatisfied with the code itself. I'm hoping someone with more experience than myself can help me come up with a more efficient and elegant solution. Please forgive my stickling :P.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ifstream i{ "data.txt" };
string key_word{ "key" };

string line;
int line_counter{ 1 };
while (getline(i, line)) {
	istringstream is{ line };
	for (string s; is >> s;) { //search each word in the line for the keyword.
		if (s == key_word) {
			cout << line_counter << ": " << line << '\n';
		}
	}
line_counter++;
}
Last edited on
A little wordier than yours, but it avoids a few allocations/copies. Keep in mind that case matters in this solution as it also does in yours.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    ifstream i{ "data.txt" };
    string key_word{ "key" };

    string line;
    int line_count = 0;
    while (getline(i, line)) 
    {
        ++line_count;

        auto pos = line.find(key_word);
        if (pos != std::string::npos)
        {
            // Avoid false positives like monkey or keyboard
            bool found = pos == 0 || std::isspace(line[pos - 1]);
            const std::size_t after = pos + key_word.size();
            found = found && (std::isspace(line[after]) || line[after] == 0);

            if (found)
                std::cout << line_count << ": " << line;
        }
    }


std::regex would be another solution, but it is probably overkill for this task.
Topic archived. No new replies allowed.