|
发表于 2023-10-15 13:05:30
|
显示全部楼层
你的代码主要问题在于你并未包含必要的头文件和未使用已定义的变量。
首先,你没有包含必要的头文件<string>和<algorithm>,这些文件中的std::string和std::count函数在此代码中被使用。
其次,你定义了变量cnt和pos,但在上面的代码中并没有使用,可能你是想在注释掉的代码中使用这些变量。
你也没有定义变量word和s的类型,虽然在此代码中不会产生错误,但是按照C++的标准,我们应该明确变量的类型,例如使用std::string word, s;。
以下是修改后的代码:
- #include <bits/stdc++.h>
- #include <string>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- int main() {
- string word, s;
- int pos = 0;
- int cnt = 0;
- getline(cin, word);
- getline(cin, s);
- s = ' ' + s + ' ';
- word = ' ' + word + ' ';
- for (int i = 0; i < s.size(); i++)
- s[i] = tolower(s[i]);
- for (int i = 0; i < word.size(); i++)
- word[i] = tolower(word[i]);
- // while (s.find(word, pos) != -1)
- // {
- // pos = s.find(word, pos) + word.size() - 1;
- // // cout<<pos<<endl;
- // cnt++;
- // }
- cnt = count(s.begin(), s.end(), word);
- // cout << ans;
- // return 0;
- if (cnt == 0)
- cout << "-1";
- else
- cout << cnt << " " << s.find(word) << endl;
- }
复制代码
这段代码现在应该可以正常运行,但请注意,如果你的输入包含空格,那么getline(cin, word);和getline(cin, s);可能会读取到两个连续的空格,因此建议使用cin >> word >> s;来读取输入。 |
|