【问题标题】:How to use functions of <strings.h> like strcmp() with object of <string.h> in c++ [duplicate]如何在c ++中使用<strings.h>的函数,如strcmp()和<string.h>的对象[重复]
【发布时间】:2020-07-02 17:27:13
【问题描述】:

我还注意到 的函数不适用于 的对象

例如在 dev c++ 中

#include<string>
#include<strings.h>
using namespace std;
int main()
{
string a="admin";
string b;
cin>>b;
if(strcmp(a,b)==0)
{
cout<<"Equal";
}
}

因此编译器在调用 strcmp() 函数的行显示错误。

[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'

这个错误实际上意味着什么以及如何解决这个问题以制作登录菜单。

请帮我解决这个问题

我也知道使用 c 类型字符串的替代方法如下,效果很好

   #include<strings.h>
    using namespace std;
    int main()
    {
    char user[32]="admin",u[32]="";
    char password[32]="admin",p[32]="";
    cout<<"\nLOGIN>>\n\nEnter User Name:";
    cin.getline(u,32);
    cout<<"Enter Password:";
    cin.getline(p,32);
    if(strcmp(u,user)==0 && strcmp(p,password)==0)
    {
cout<<"Match";
}
}

但我想比较 的对象,而不是数组。

【问题讨论】:

  • 只使用a == b有什么问题?
  • 什么是strings.h? C 仅包含 string.h 或在 C++ 中您应该使用 cstring(不包含扩展名)
  • 请注意,cstring 是 C 编程语言中 string.h 的 c++ 版本。 C 没有std::string,因此C 函数与std::string 交互的能力是有限的。
  • 非常感谢先生 a==b 工作正常。我不知道
  • 先生,我们可以使用赋值运算符复制这些字符串吗?

标签: c++ string authentication copy compare


【解决方案1】:

strcmp 作用于 c-strings,而不是 std::strings。

要访问 std::string 的内部 c 字符串,请使用 c_str() method

if (strcmp(a.c_str(), b.c_str()) == 0) {
 // ...
}

不过你也可以do the comparison directly

if (a == b) {
  // ...
}

【讨论】:

【解决方案2】:

这是因为函数strcmp()向程序员询问参数:

const char *, const char *

但你试图传递如下参数:

std::string, std::string

但该函数需要const char *

要解决这个问题,您需要在std::string 之后使用.c_str()

试试这个方法:

if (strcmp(a.c_str(), b.c_str()) == 0)

这会将整个std::string 对象转换为const char * 类型。

当你必须使用strcmp()或者需要const char *类型的函数时使用这个。否则推荐的方式如下。


您甚至不需要使用strcmp(),因为std::string 具有比较运算符,因此您可以计算与以下相同的表达式:

if (a == b)

如果字符串对象a 等于b,它将变为真。

【讨论】:

  • c_str() 在现代 C++ 中不进行任何转换。它仅提供对std::string 内部缓冲区的访问。即使在不提供内部缓冲区的旧 C++ 实现中也非常罕见,以至于我认为我从未见过。
  • @user4581301 也许你刚才看到了。
  • 非常感谢先生
  • @RohanBari 在过去的一年中,我终于设法让我公司的所有 C++ 代码至少达到 C++11。我很安全。
猜你喜欢
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
相关资源
最近更新 更多