你没有按照你得到的指示去做。
具体来说,您缺少以下条件的代码:
提示:如果没有找到正在搜索的项目,find() 返回 string::npos。
您没有检查 for 的返回值find()(npos定义为string::size_type(-1))。
find()返回找到的子字符串的索引的数值,或者npos如果没有找到。
该语句if (userInput.find("darn"))正在检查零与非零索引值。在所有三个测试用例中,find()都不会返回索引 0,因此任何非零值都会导致if语句评估为 astrue并进入"Censored"块。
此活动将执行三个测试,用户输入为“那只该死的猫。”,然后是“Dang,那太可怕了!”,然后是“我在织补你的袜子”。
您只执行第一个测试,而不执行其他测试。
试试这个:
#include <iostream>
#include <string>
using namespace std;
int main() {
string userInput;
userInput = "That darn cat.";
if (userInput.find("darn") != string::npos) {
cout << "Censored" << endl;
}
else {
cout << userInput << endl;
}
userInput = "Dang, that was scary!";
if (userInput.find("darn") != string::npos) {
cout << "Censored" << endl;
}
else {
cout << userInput << endl;
}
userInput = "I'm darning your socks.";
if (userInput.find("darn") != string::npos) {
cout << "Censored" << endl;
}
else {
cout << userInput << endl;
}
return 0;
}
然后可以使用可重用函数重写:
#include <iostream>
#include <string>
using namespace std;
void checkInput(const string &input) {
if (input.find("darn") != string::npos) {
cout << "Censored" << endl;
}
else {
cout << input << endl;
}
}
int main() {
string userInput;
userInput = "That darn cat.";
checkInput(userInput);
userInput = "Dang, that was scary!";
checkInput(userInput);
userInput = "I'm darning your socks.";
checkInput(userInput);
return 0;
}