首页 文章

为什么错误“从'char'无效转换为'const char *”? [重复]

提问于
浏览
1

可能重复:C将char转换为const char *

我有一个代码片段:

string opposite(string c)
{
    if(c == (string) "\""){return "\"";}
    if(c == (string) "<"){return ">";}
    throw;
}

int load_end(int start, string code)
{
    //start is the begining of "header.h" or <header> in #load "header.h" or #load <header>
    //code is self explanitory
    //This function returns the end of "header.h" or <header> in #load "header.h" or #load

    string chr = " ";
    int e;
    string asdf = opposite(code[start]);
    for(int i = start; chr == asdf; i++)
    {
        e = i;
        chr = code[i];
    }
    return e;
}

在定义'asdf'的单词的行处发生错误; “从'char'无效转换为'const char *'[-fpermissive]” . 还会发生另一个错误:“c:\ mingw \ bin .. \ lib \ gcc \ mingw32 \ 4.6.2 \ include \ c \ bits \ basic_string.tcc | 214 |错误:初始化'std :: basic_string <_CharT,_Traits,_Alloc> :: basic_string(const _CharT *,const _Alloc&)的参数1 [_CharT = char,_Traits = std :: char_traits,_Alloc = std :: allocator]'[-fpermissive] |“ . 这些错误对我来说没有任何意义 .

2 回答

  • 2

    问题是,正如编译器有用地告诉我们的那样,您正在发送一个字符的地址,其中相反的函数需要一个字符串 .

    • 首先让's address a few issues in your code, always make the function return something for the other cases, if the function has a return value.What does your opposite function return if both the if conditions fail, think about it.Maybe you could return a error string or a null string.That'总是一个整洁的编码风格 .

    • 其次,这是一个更关键的一点,为什么你有一个字符串并且返回一个字符串,当它实际上接受一个字符并返回一个字符串时,它具有相反的功能?

    • 其他可能的问题是chr未初始化 . 这里chr的作用是什么?如果你能纠正上述问题,并澄清一点,我们可以帮助你 .

  • 1

    string[index] 正在返回一个字符而不是字符串

    看看文档:http://www.cplusplus.com/reference/string/string/operator%5B%5D/

    试图解决它:

    char opposite(const char c)
    {
        if(c == '<')
        {
           return '>';
        }
        return c; // (c == '"') { return '"'; }
    }
    
    int load_end(int start, string code)
    {
        //This function returns the end of "header.h" or <header> in #load "header.h" or #load <header>
        char chr = 0;
    
        for(int i = start; chr == opposite(code[start]); i++)
        {
            chr = code[i];
        }
        return 0;
    }
    

相关问题