如何在 c++ 中将字符串与指针中的字符串进行比较

How to compare a string with a string in pointer in c++

本文关键字:字符串 比较 指针 c++      更新时间:2023-10-16

我正在用c ++实现链表。在那,我试图将存储在节点中的数据与字符串进行比较。这是我的代码:

String f; 
cin>>f; 
if(strcmp(temp->data,f)==0) 
    {  cout<<"same"; } 
else 
    { cout<<"not same"; }

这是我的错误:

"assignment1.cc", line 160: Error: Cannot cast from std::string  to const char*.
"assignment1.cc", line 160: Error: Cannot cast from std::string  to const char*.

如何比较这两个字符串?

如果你只需要检查相等性,你可以简单地使用operator==来比较两个string s。在您的情况下,这似乎是:

if (data->temp == f)

但是,如果你想要strcmp提供的功能(也就是说,如果你需要知道哪个字符串在字典顺序上更大,以防它们不相等),你可以使用 string::compare

if ( s1.compare(s2) < 0 )

您可以使用 std::string::c_str 方法:

std::string f; 
cin>>f; 
if(strcmp(temp->data,f.c_str())==0) 
    cout<<"same";
else 
    cout<<"not same";

您可以使用 f 的 "compare()" 运算符 (http://en.cppreference.com/w/cpp/string/basic_string/compare),也可以使用运算符 ==

#include <iostream>
#include <string>
int main() {
    std::string f("hello world");
    const char* p = "hello world";
    if (f == p)
        std::cout << "f == p" << std::endl;
}

请参阅 http://ideone.com/TTXRZv