-2

如果 userInput 包含单词“darn”,则打印“Censored”,否则打印 userInput。以换行符结束。提示:如果没有找到正在搜索的项目,find() 返回 string::npos。

注意:这些活动可能会使用不同的测试值测试代码。此活动将执行三个测试,用户输入为“那只该死的猫。”,然后是“Dang,那太可怕了!”,然后是“我在织补你的袜子”。

这是我尝试过的代码。我真的不知道还能尝试什么。

#include <iostream>
#include <string>
using namespace std;

int main() {
   string userInput;

   userInput = "That darn cat.";

   if (userInput.find("darn")) {
      cout << "Censored" << endl;
   }

   else {
      cout << userInput << endl; 
   }

   return 0;
}

userInput应该导致Censored如果它包含"darn". 否则,它应该打印userInput.

我的结果说明Censored了每个输入。

4

1 回答 1

1

你没有按照你得到的指示去做。

具体来说,您缺少以下条件的代码:

  • 提示:如果没有找到正在搜索的项目,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;
}
于 2019-04-05T18:45:56.050 回答