写的代码错在哪了,学生党qaq了

编写一个c++程序,读入一个搜索词,然后读入几个以字符结尾的词。程序应该计算这个搜索词在
文本中出现的次数。假设没有标点符号。例子:
输入搜索词:cat
输入一些单词(以
结尾):That cat is a mad cat *
单词cat出现了2次。

#include<iostream>
#include<string>
using namespace std;
int main(){int count=0;
    string searchword,text;
    cout<<"Enter searchword:";
    cin>>searchword;
    cout<<"Enter a text(the text's end is *):";
    while(getline(cin,text))
    {
        if (text[text.size()-1]=='*'){
            int a=0;
            while ((a=text.find(searchword)) != string::npos)
        {count++; 
         a+=searchword.length();
        }
        }
    }
cout<<"the word have "<<count<<" in the text";
    return 0;
    }

问GPT的回答:

1.输入搜索词和一些单词时,使用了 getline(cin, text) 读取整行输入,而题目要求以空格为结尾的单词,应该使用 cin >> text 来读取。

2.在查找 searchword 在 text 中出现的次数时,使用了一个循环和 find() 方法,但是该方法无法解决查找重叠字符串的情况。

3.在输出结果时,结果中应该是 “单词” 而不是 “the word”。

以下是一个修改后的程序:


#include<iostream>
#include<string>
using namespace std;
int main() {
    int count = 0;
    string searchword, text;
    cout << "Enter searchword: ";
    cin >> searchword;
    cout << "Enter a text (the text's end is *): ";
    while (cin >> text) {
        if (text[text.size() - 1] == '*') { // 判断是否读取到了结尾符 *
            size_t pos = 0;
            while ((pos = text.find(searchword, pos)) != string::npos) { // 使用 find() 方法查找字符串
                count++;
                pos += searchword.length();
            }
            break;
        }
    }
    cout << "The word \"" << searchword << "\" appears " << count << " times in the text." << endl;
    return 0;
}