如何在 c++ 中将字符串与指针中的字符串进行比较
How to compare a string with a string in pointer in c++
我正在用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
相关文章:
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 字符串比较中的意外输出
- 如何执行不区分大小写的字符串比较?
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- <<运算符优先级与字符串比较
- ">"运算符和"<"运算符如何进行字符串比较?
- Qt C++11 字符串通过子字符串比较列出交集
- std::out_of_range字符串比较中的异常
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 字符* 与uint8_t的字符串比较
- 用字符串 c++ 比较对向量的元素
- 使用循环进行词典字符串比较
- 如何为C++映射创建自己的字符串比较对象
- 不带比较()的字符串比较
- 与 IF 语句C++的字符串比较?
- 字符串比较在与变量一起使用时给出不同的输出
- 更快的字符串比较排序,用于唯一()
- C 字符串比较“祝您好运”&gt;“再见”
- C 奇怪的行为和字符串比较
- 子字符串与 std::memcmp 或字符串::比较的比较