如何将字符串与const char*进行比较?

16
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
        string cmd;
        while(strcmp(cmd.c_str(),"exit")==0 && strcmp(cmd.c_str(),"\exit")==0)
        {
                cin>>cmd;
                cout<<cmd;
        }
        return 0;
}

我被卡住了。


1
最好直接将代码粘贴在问题中。 - Brian R. Bondy
1
此外,如果您使用cmd.compare("exit")而不是strcmp(cms,c_str(),"exit")==0,代码会更加简洁。您正在编写C++代码。何不充分利用它呢? - Vagrant
3
STL为const char*提供了operator==,为什么不使用它? - Stephen
@Stephen:实际上,std::string不是来自于那个从STL演进而来的标准库部分。否则你肯定是对的。 - sbi
6个回答

20

使用!===运算符,可以直接将std::string实例与字符串字面值进行比较。这会使您的比较更清晰明了。

请注意,\e不是有效的字符转义,如果你要表示字面值\\,需要将\加倍。

while( cmd == "exit" && cmd == "\\exit" )

显然,cmd 不能同时等于两个不同的字符串,你可能是想用 !=

另外,请考虑使用 std::getline(std::cin, cmd) 是否比使用 std::cin >> cmd; 更合适。在任何情况下,您都应该检查读取操作是否成功,否则如果流被关闭或进入了失败状态,您可能会陷入无限循环中。

就我个人而言,我会选择像这样的代码,假设你想回显退出命令:

#include <string>
#include <iostream>
#include <ostream>

int main()
{
    std::string cmd;
    while (std::getline(std::cin, cmd))
    {
        std::cout << cmd << std::endl;
        if (cmd == "exit" || cmd == "\\exit")
            break;
    }
    return 0;
}

15

修复了几个小错误后,这在我的电脑上可以工作:

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>

int main()
{
        std::string cmd;
        while( std::strcmp(cmd.c_str(),"exit")!=0
            && std::strcmp(cmd.c_str(),"\\exit")!=0)
        {
                std::cin>>cmd;
                std::cout<<cmd << '\n';
        }
        return 0;
}

然而,我想知道为什么你想使用 std::strcmp()。正如你刚刚发现的那样,它不像 std::string 类那样易于使用。这

while(cmd!="exit" && cmd!="\\exit")

这样做同样有效,更易理解,因此更容易正确实现。


1
在比较之前,OP可能想要将输入字符串转换为小写。这允许用户键入“Exit”和“exit”。需要研究的术语是:std::transformtolower - Thomas Matthews
1
在Unixy(也许在Windows上)系统中还有strcasecmp,它忽略大小写。 - Joe

5

strcmp函数在两个参数相等的时候返回0。所以我认为你想要使用!= 0。

当然,strcmp不可能同时等于两个参数,因此不会同时返回0。

此外,看起来你的字符串开头有一个反斜杠,你应该使用双反斜杠进行转义。


2
你的 while 循环条件永远不会被评估为 true,因为你正在测试 cmd 字符串是否等于 "exit" "\\exit"。一个字符串不能同时等于两个值。

1

你的问题在于 while 条件。

当用户输入 exit 时,你可能想要退出循环,所以你应该使用:

while(strcmp(cmd.c_str(),"exit")!=0 && strcmp(cmd.c_str(),"\exit")!=0)

-2

请记住以下几点,我重申一些值得重复的建议,while(1)次。

  1. 您正在使用C++,它是面向对象的,即最好将数据和处理数据的函数组合在一起。在这种情况下,使用string类提供的字符串比较选项,而不是strcmp。

  2. 您的程序存在逻辑错误,虽然它可以编译,但恐怕这不是您想要的。if ( a == x && a == y ) 这将始终为false,因为a不能同时等于x和y,除非x=y,在您的情况下显然x!=y。

祝好, Pavan


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接