【问题标题】:string.find() doesn't work properly [closed]string.find() 无法正常工作 [关闭]
【发布时间】:2018-06-07 19:56:54
【问题描述】:

大家好,我正在尝试制作输入输出 AI,并且正在尝试输入的一些可能性,因此我正在尝试 string.find()。但有时我写句子时它不起作用,可能是因为空格。你能看看并告诉我出了什么问题,或者只是告诉我用什么来代替 string.find?()?

    std::string sentence;

std::cin >> sentence;

if (sentence.find("what") != std::string::npos)
{
    if (sentence.find("are") != std::string::npos)
    {
        if (sentence.find("you") != std::string::npos)
        {
            if (sentence.find("?") != std::string::npos)
            {
                std::cout << "I am an AI" << std::endl;
            }
        }
    }
}

【问题讨论】:

  • 请编辑您的问题以包含minimal reproducible example
  • 有什么问题?
  • "string.find() 不能正常工作" - std::string::find 工作正常 - 如果你知道如何使用它并在正确的数据上使用它。
  • cin &gt;&gt;sentence; 之后放置cout &lt;&lt;sentence; 会让您走上解决此问题的好方法。调试时要做的第一件事就是收集信息。
  • @user4581301 就像使用调试器一样......

标签: c++ artificial-intelligence stdstring


【解决方案1】:

c++ 的cin 提示符会抓取任何字符,直到找到空格、换行符或其他描述字符。试试std::getline()

std::string sentence;
std::getline(std::cin, sentence);

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2013-05-23
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多