将字符序列的内容存入字符串变量C++时无法进行比较
首先,我正在学习 C++,需要您帮助解决我遇到的问题... 我有以下代码:
std::string var2;
std::string MSG1="1";
char charSeq[1024];
cout << charSeq << endl;
var2 = charSeq;
cout << var2 << endl;
上面的代码满足了我的要求,即获取名为 charSeq 的字符序列的内容并将它们放入名为 var2 的字符串变量中 但是当我想对字符串变量var2进行比较或任何操作时,我不能,例如,如果charSeq的值为1,并且我将这个值赋给var2,那么我在MSG和var2之间进行比较,结果是总是错误的,比如 var2 没有值或者有错误的值...
if (var2==MSG1)
{
// the code here never gets executed, even when the values are the same in var2 and MSG...
}
else
{
// the result is always false and this condition executed no matter what var2 and MSG values were...
}
你能帮我提供一些关于这方面的提示吗?
First, I am learning C++, and need your help with an issue I have...
I have the following piece of code:
std::string var2;
std::string MSG1="1";
char charSeq[1024];
cout << charSeq << endl;
var2 = charSeq;
cout << var2 << endl;
The above does for me what I want, which is taking the contents of the character sequence named charSeq and put them in the string variable named var2
But when I want to do comparison or any operation on the string variable var2, I cannot, for example, if charSeq has the value of 1, and I assigned this value to var2, then I made comparison between MSG and var2, the result is always false, like var2 has no value or has a wrong value...
if (var2==MSG1)
{
// the code here never gets executed, even when the values are the same in var2 and MSG...
}
else
{
// the result is always false and this condition executed no matter what var2 and MSG values were...
}
Can you help me with some tips on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在阅读了上面 Seth 的评论后(非常感谢您的长度提示),我设法解决了这个问题:
我在 charSeq 中有 2 个不可见的字符,这些字符被复制到 var2,这导致了比较的错误结果,我所做的是:
再次感谢大家......
After reading the comment from Seth above (thank you very much for the tip of the length), I managed to solve the issue:
I was having 2 invisible characters in charSeq, and those were copied to var2, this was causing the false result of the comparison, what I did is:
Thanks again for all of you...