我只是在使用我最近学到的一些东西在C ++中乱搞,我想知道如何正确地比较两个字符串。我查看了前一个帖子寻求帮助,但我不确定我是否正确获取变量并且存在重复错误。 (P.S.这将在命令提示符下执行。)
string Users = "Username1";
//Set an empty string.
string UserChoice;
//Print out a line that warns the user to type a user.
std::cout << "Username: ";
std::cin >> UserChoice;
//If the user types out whatever "Users" is, run the code below.
if (strcmp(Users, UserChoice) == 0){
//Do Stuff
}
答案 0 :(得分:7)
你想:
if (Users == UserChoice) {
std :: string类(好吧,实际上是std :: basic_string)重载了==运算符(以及许多其他运算符)以执行您想要的操作。您不应该在C ++代码中使用类似strcmp的C函数,并且无论如何它们都不能直接应用于C ++ std :: strings。
答案 1 :(得分:0)
比较字符串与比较int值,char值等相同。您应该使用以下方法:
string a
string b
if (a == b)
{
// Do something
}
在您的情况下,&#39; a&#39;和&#39; b&#39;将被&#39;用户&#39;用户选择&#39;取代。但是,无论类型如何,比较相同类型的2个变量的基本格式都保持不变(我不确定此规则是否有任何例外)。
正如@latedeveloper所提到的那样,也建议不要在c ++程序中使用c语言函数。这两种语言不可互换!
**有用的提示:始终努力使代码尽可能简单。除了一些例外情况,您制作代码越复杂,您就越难以让其他人理解您的代码。要将它连接到您的案例,为什么使用函数strcmp()时可以通过使用==符号来保持简单?根据个人经验,这只是我的2位。
答案 2 :(得分:-2)
c style:
string a
string b
if(strcmp(a.c_str(),b.c.str()) == 0)