【发布时间】: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?) 更好。