C ++比较字符串? ==运算符不工作 [英] C++ Compare string ? == operator not working

查看:86
本文介绍了C ++比较字符串? ==运算符不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个,这是行不通的。尝试用cout打印两个字符串,它们看起来完全一样。尝试str.find,strcmp也是。

I got this, which is not working. Tried printing both strings with cout, and they look exactly the same. tried str.find, strcmp also.

string MyWebResponse = client.GetResponse();
string hash = HASH(token + time + user + password + salt);
/*
MyWebResponse = 5accdd72bb566079faf459cbad0934c5
and
hash          = 5accdd72bb566079faf459cbad0934c5

tho, I can't get my program to recognize they're exactly the same

*/
if(MyWebResponse == hash){
    //Do something, but it never gets there.
}

推荐答案

当然'==' operator 可以正常工作。这意味着你实际上并没有观察正确的字符串值。正如<乔治·斯旺指出的那样,在其中一个(或两个)中可能存在虚假控制字符,导致不匹配。

尝试,例如

Of course the '==' operator does work. That means you are not actually observing the correct string values. As pointed out by George Swan there could be spurious control characters in one (or both) of them, causing the mismatch.
try, for instance
 #include <iostream>
 #include <string>
using namespace std;

void dump( string s)
{
  for (unsigned int n=0; n<s.length(); ++n)
  {
    char c = s[n];
    cout << (int) c << ",";
  }
  cout << endl;

}

int main()
{

  string s1 = "asaaaa\r";
  string s2 = "asaaaa\n";
  cout << s1 << endl;
  cout << s2 << endl;

  dump(s1);
  dump(s2);
}


您的字符串中可能有控制字符 。尝试清理它们。

string MyWebResponse = "5accdd72bb566079faf459cbad0934c5";
string cleanedResponse=  new string(MyWebResponse.Where(c=>!char.IsControl(c)).ToArray());


尝试 strcmp


这篇关于C ++比较字符串? ==运算符不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆