Garmaine Staff asked 2 years ago

When you use a specific keyword, it is a matter of printing out all the words that contain that keyword. You shouldn't use arrays in solving problems.

I used the find() function to get the code that prints from the starting index of the keyword until ',' appears, but there is an error.



Here is the code:

#include <iostream>
#include <string>
#include <limits.h>
using namespace std;

int main() {
    string data = "사랑,프로그래머,의자,사랑의바보,영통역,천년의사랑,냉장고,객체지향";
    string keyword;
    cout << "키워드 : ";
    cin >> keyword;
    int i = 0;
    while (1) {
        i = data.find(keyword, i);
        if (i == INT_MAX) return 0;
        while (data[i] != ',') {
            cout << data[i] << " ";

Even if it compiles successfully, if the keyword is after the word, it cannot be printed.

In summary, my questions are:

  1. Problems in the above code, assuming the keyword is in front of the word.

  2. Idea to print the word even when the keyword is behind it.