将字符序列的内容存入字符串变量C++时无法进行比较

发布于 2024-12-17 11:06:52 字数 678 浏览 2 评论 0原文

首先,我正在学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

許願樹丅啲祈禱 2024-12-24 11:06:52

在阅读了上面 Seth 的评论后(非常感谢您的长度提示),我设法解决了这个问题:
我在 charSeq 中有 2 个不可见的字符,这些字符被复制到 var2,这导致了比较的错误结果,我所做的是:

cout << "charseq length: " << strlen(charSeq) << endl;
cout << "var2 length: " << var2.length() << endl;

var2.erase(var2.length()-2,var2.length()); //here is what i did...

cout << "var2 new length: " << var2.length() << endl; // the result was the correct length of the visible characters, and the comparison condition was executed...

再次感谢大家......

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:

cout << "charseq length: " << strlen(charSeq) << endl;
cout << "var2 length: " << var2.length() << endl;

var2.erase(var2.length()-2,var2.length()); //here is what i did...

cout << "var2 new length: " << var2.length() << endl; // the result was the correct length of the visible characters, and the comparison condition was executed...

Thanks again for all of you...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文