比较 C++ 中的字符文字与 Std::String

发布于 2024-09-16 23:04:55 字数 1807 浏览 7 评论 0原文

我想将字符文字与字符串的第一个元素进行比较,以检查文件中的注释。为什么使用字符?我想把它变成一个函数,它接受字符 var 作为注释。我不想允许使用字符串,因为我想将其长度限制为单个字符。

考虑到这一点,我认为最简单的方法是寻址字符并将其传递给 std::string 的比较函数。然而,这给了我意想不到的结果。

我的代码如下:

#include <string>
#include <iostream>

int main ( int argc, char *argv[] )
{
  std::string my_string = "bob";
  char my_char1 = 'a';
  char my_char2 = 'b';

  std::cout << "STRING : " << my_string.substr(0,1) << std::endl
        << "CHAR : " << my_char1 << std::endl;
  if (my_string.substr(0,1).compare(&my_char1)==0)
    std::cout << "WOW!" << std::endl;
  else
    std::cout << "NOPE..." << std::endl;

  std::cout << "STRING : " << my_string.substr(0,1) << std::endl
        << "CHAR : " << my_char2 << std::endl;
  if (my_string.substr(0,1).compare(&my_char2)==0)
    std::cout << "WOW!" << std::endl;
  else
    std::cout << "NOPE..." << std::endl;

  std::cout << "STRING : " << my_string << std::endl
        << "STRING 2 : " << "bob" << std::endl;
  if (my_string.compare("bob")==0)
    std::cout << "WOW!" << std::endl;
  else
    std::cout << "NOPE..." << std::endl;
}

给我...

STRING : b
CHAR : a
NOPE...
STRING : b
CHAR : b
NOPE...
STRING : bob
STRING 2 : bob
WOW!

为什么函数认为子字符串和字符不一样。正确比较字符和 std::string 变量的最短方法是什么?

(简短的咆哮是为了避免对我的问题重新分类......请随意跳过)
当我说最短时,我的意思是出于对编码口才的渴望。请注意,这不是一个家庭作业问题。我是一名化学工程博士候选人,正在编码作为独立研究的一部分。当我询问我的最后一个问题时,用户msw(他也发表了讽刺评论)将我的最后一个问题重新分类为“家庭作业”效率,我认为这处于滥用的边缘。我的代码可能会也可能不会被其他人重用,但我正在努力使其易于阅读和维护。我还有一个奇怪的愿望,就是让我的代码尽可能高效。因此,关于效率和口才的问题。

I would like to compare a character literal with the first element of string, to check for comments in a file. Why use a char? I want to make this into a function, which accepts a character var for the comment. I don't want to allow a string because I want to limit it to a single character in length.

With that in mind I assumed the easy way to go would be to address the character and pass it to the std::string's compare function. However this is giving me unintended results.

My code is as follows:

#include <string>
#include <iostream>

int main ( int argc, char *argv[] )
{
  std::string my_string = "bob";
  char my_char1 = 'a';
  char my_char2 = 'b';

  std::cout << "STRING : " << my_string.substr(0,1) << std::endl
        << "CHAR : " << my_char1 << std::endl;
  if (my_string.substr(0,1).compare(&my_char1)==0)
    std::cout << "WOW!" << std::endl;
  else
    std::cout << "NOPE..." << std::endl;

  std::cout << "STRING : " << my_string.substr(0,1) << std::endl
        << "CHAR : " << my_char2 << std::endl;
  if (my_string.substr(0,1).compare(&my_char2)==0)
    std::cout << "WOW!" << std::endl;
  else
    std::cout << "NOPE..." << std::endl;

  std::cout << "STRING : " << my_string << std::endl
        << "STRING 2 : " << "bob" << std::endl;
  if (my_string.compare("bob")==0)
    std::cout << "WOW!" << std::endl;
  else
    std::cout << "NOPE..." << std::endl;
}

Gives me...

STRING : b
CHAR : a
NOPE...
STRING : b
CHAR : b
NOPE...
STRING : bob
STRING 2 : bob
WOW!

Why does the function think the sub-string and character aren't the same. What's the shortest way to properly compare chars and std::string vars?

(a short rant to avoid reclassification of my question.... feel free to skip)
When I say shortest I mean that out of a desire for coding eloquence. Please note, this is NOT a homework question. I am a chemical engineering Ph.D candidate and am coding as part of independent research. One of my last questions was reclassified as "homework" by user msw (who also made a snide remark) when I asked about efficiency, which I considered on the border of abuse. My code may or may not be reused by others, but I'm trying to make it easy to read and maintainable. I also have a bizarre desire to make my code as efficient as possible where possible. Hence the questions on efficiency and eloquence.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

思念满溢 2024-09-23 23:04:56

这样做:

  if (my_string.substr(0,1).compare(&my_char2)==0)

不会起作用,因为您“欺骗”字符串,使其认为它正在获取指向以 null 结尾的 C 字符串的指针。这会产生奇怪的影响,甚至包括导致程序崩溃。相反,只需使用正常的相等将字符串的第一个字符与 my_char 进行比较:

 if (my_string[0] == my_char)
   // do stuff

Doing this:

  if (my_string.substr(0,1).compare(&my_char2)==0)

Won't work because you're "tricking" the string into thinking it's getting a pointer to a null-terminated C-string. This will have weird effects up to and including crashing your program. Instead, just use normal equality to compare the first character of the string with my_char:

 if (my_string[0] == my_char)
   // do stuff
初与友歌 2024-09-23 23:04:56

为什么不在字符串上使用索引运算符呢?它将返回一个 char 类型。

if (my_string[0] == my_char1)

Why not just use the indexing operator on your string? It will return a char type.

if (my_string[0] == my_char1)
陌若浮生 2024-09-23 23:04:56

您可以使用字符串的运算符[]将其与单个字符进行比较

// string::operator[]
#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string str ("Test string");
    int i; char c = 't';
    for (i=0; i < str.length(); i++)
    {
        if (c == str[i]) {
            std::cout << "Equal at position i = " << i << std::endl;
        }
    }
    return 0;
}

You can use the operator[] of string to compare it to a single char

// string::operator[]
#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string str ("Test string");
    int i; char c = 't';
    for (i=0; i < str.length(); i++)
    {
        if (c == str[i]) {
            std::cout << "Equal at position i = " << i << std::endl;
        }
    }
    return 0;
}
南汐寒笙箫 2024-09-23 23:04:56

前两次比较调用的行为完全取决于每个字符地址后面的随机内存内容。您正在调用 basic_string::compare(const char*) ,并且此处的参数假定为 C 字符串(以 null 结尾),而不是单个字符。 compare() 调用将比较您想要的字符,然后是该字符之后内存中的所有内容,直到下一个 0x00 字节,以及手中的 std::string。

奥托《》运算符确实对 char 输入有适当的重载,因此您的输出并不反映您在此处实际比较的内容。

将 和 b 的声明转换为 const char[] a = "a"; 你就会得到你想要的结果。

The behaviour of the first two calls to compare is entirely dependent on what random memory contents follows the address of each char. You are calling basic_string::compare(const char*) and the param here is assumed to be a C-String (null-terminated), not a single char. The compare() call will compare your desired char, followed by everything in memory after that char up to the next 0x00 byte, with the std::string in hand.

Otoh the << operator does have a proper overload for char input so your output does not reflect what you are actually comparing here.

Convert the decls of and b to be const char[] a = "a"; and you will get what you want to happen.

北凤男飞 2024-09-23 23:04:56

非常标准,C++ 中的字符串以 null 结尾;字符不是。因此,通过使用标准比较方法,您实际上是在检查“b\0”是否等于“b”。

我使用了它并得到了所需的输出:

if (my_string.substr(0,1).compare( 0, 1, &my_char2, 1)==0 )
    std::cout << "WOW!" << std::endl;
else
    std::cout << "NOPE..." << std::endl;

这意味着从子字符串的位置 0 开始,使用长度 1,并将其与长度为 1 的字符引用进行比较。 参考

Pretty standard, strings in c++ are null-terminated; characters are not. So by using the standard compare method you're really checking if "b\0" == 'b'.

I used this and got the desired output:

if (my_string.substr(0,1).compare( 0, 1, &my_char2, 1)==0 )
    std::cout << "WOW!" << std::endl;
else
    std::cout << "NOPE..." << std::endl;

What this is saying is start at position 0 of the substring, use a length of 1, and compare it to my character reference with a length of 1. Reference

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