-3

I've written the following program to match regular expressions in C++

#include <regex.h>
#include <iostream>

using namespace std;

/*
* Match string against the extended regular expression in
* pattern, treating errors as no match.
*
* return true for match, false for no match
*/


bool match(const char *string, char *pattern)
{
    int status; regex_t re;

    if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
        return false;
    /* report error */

    status = regexec(&re, string, (size_t) 0, NULL, 0);
    regfree(&re);
    if (status != 0) {
        return false; /* report error */
    }
    return true;
}

int main()
{
    string str = "def fadi 100";
    bool matchExp = match(str.c_str(), "^[Dd][Ee][Ff][' '\t]+[A-z]+([,])?[''\t]+[0-9]+$");
    cout << (matchExp == true ? "Match": "No match") << endl;
}

The program works fine just as expected, but when I compile the code using gcc with the -Wall -Werror arguments (Linux environment), I get a very annoying warning message saying the following:

main.cpp: In function ‘int main()’:
main.cpp:33:90: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

Is there a way to force the compiler to believe that str.c_str() is the same as char * str? if so, how?

4

4 回答 4

8

不,没有。该转换在 C++03 中已弃用,在 C++11 中是非法的;不要这样做。

弃用该转换的原因是字符串文字是只读的,因此const; 使用指向 non- 的指针访问它们const char可能会导致修改const对象,从而调用未定义的行为。警告并不烦人;它旨在使您免于使您的应用程序崩溃 - 或更糟。

另外,您在阅读警告信息时是错误的;这不是关于c_str(),而是关于将字符串文字传递为char *.

真正修复代码的唯一方法是将您的第二个参数更改match为 be const char *, not char *,并将传递的字符串复制到该函数内部的新缓冲区(为什么不 in main()?因为使用内部缓冲区,您的样板文件更少调用方)。


我还想提出完全不同的解决方案,因为问题被标记为“C++”:Boost.Regex

于 2013-06-26T18:22:23.907 回答
2

有没有办法强制编译器相信它与strstr.c_str()相同?char *

这实际上不是这里的问题 - 你已经str.c_str()作为const char*.

问题是第二个参数(也是)一个字符串文字,但具有 type char*。尝试将第二个参数更改为const char*.

如果这仍然引发错误(由于regex.h函数未指定正确的 const-ness),您将不得不在main()or中执行类似的操作match()

char pattern[] = "^[Dd][Ee]...etc";
bool matchExp = match(str.c_str(), pattern);

原因见这里。

于 2013-06-26T18:29:11.013 回答
1

使函数的2个参数匹配const char *,警告是因为它

于 2013-06-26T18:27:32.227 回答
1

问题是字符串文字应该只分配给 const char 的指针,因此您需要更改 match 以采用 char const* 模式(这在您传递字符串文字时应该是可能的)

于 2013-06-26T18:22:07.337 回答