【问题标题】:How to use "in" keyword in c++如何在 C++ 中使用“in”关键字
【发布时间】:2020-12-10 18:20:10
【问题描述】:

嘿,我是一个新的 C++ 学习者,我一直在创建一个程序来做一些特定的事情...... 我从用户那里获取输入,并将其转换为小写的句子,然后我使用我们在 python 中使用的“in”关键字......例如在 python 中:

main_input = input("Type exit with a bunch of other words: ")
lower_input = main_input.lower()
if "exit" in lower_input:
    exit()
else:
    pass

它的作用是从输入中搜索退出关键字(如“ok you can exit now”)并相应地退出程序。 但是如何在 C++ 中使用“in”关键字呢? 我想做这样的事情

#include <iostream>
#include "boost/algorithm/string.hpp"
using namespace std;

int main() {

    while(true){
        std::string main_input;
        std::cout << "Type something: ";
        std::cin >> main_input;
        std::string lower_input = boost::algorithm::to_lower_copy(main_input);
/* the if statement below this, here is the problem...*/
        if("exit" in lower_input){
            std::cout << "Exiting";
            /* after that other statements if necessary to execute*/

        }

    }
  
}

谁能告诉我该怎么做?提前致谢!

【问题讨论】:

  • 您可以使用find,或者如果您想要完全匹配 - 只需简单的旧==...
  • "但是如何在c++中使用"in"关键字?" C++中没有in关键字。
  • O.T.:我很欣赏您在每个标准内容前加上其范围 std:: 的事实。然而,这使得接近顶部的using namespace std; 更加烦人...... ;-)
  • @ROG_SHAKHYAR 如果你正在学习 C++,请考虑向 good C++ book 学习,因为 undefined behavior 的各种情况,你不能仅仅通过“乱搞”来学习它。
  • 说实话:用std:: 前缀标准的东西是完全可以的,比using namespace std; (Why is “using namespace std;” considered bad practice?) 更好。

标签: python c++ string stl


【解决方案1】:

可以使用std::string类的成员函数find

类似

if ( lower_input.find( "exit" ) != std::string::npos ){

但是写起来会更准确

if ( lower_input == "exit" ) {

因为用户可以输入一个包含“exit”符号的句子,而无意中断循环。

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2014-04-24
    • 2021-03-14
    • 2014-03-30
    • 2014-08-18
    相关资源
    最近更新 更多