C ++错误从函数返回一个字符串

时间:2018-05-02 10:41:03

标签: c++ string

我正在尝试从函数solution()返回一个字符串,但我收到的错误如下。抱歉,如果这是非常基本的,但任何人都可以解释如何返回字符串。我知道它与指针有关。

  

错误:无法转换'(std :: __ cxx11 :: string *)(& hexaDeciNum)'来自   'std :: __ cxx11 :: string * {aka std :: __ cxx11 :: basic_string *}'to   'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}'

string solution(string &S){

    int n = stoi(S);
    int answer = 0;

    // char array to store hexadecimal number
    string hexaDeciNum[100];

    // counter for hexadecimal number array
    int i = 0;
    while(n!=0)
    {
        // temporary variable to store remainder
        int temp  = 0;

        // storing remainder in temp variable.
        temp = n % 16;

        // check if temp < 10
        if(temp < 10)
        {
            hexaDeciNum[i] = temp + 48;
            i++;
        }
        else
        {
            hexaDeciNum[i] = temp + 55;
            i++;
        }

        n = n/16;
    }

    // printing hexadecimal number array in reverse order
    for(int j=i-1; j>=0; j--){
        //cout << hexaDeciNum[j] << "\n";

    if (hexaDeciNum[j].compare("A") ==0 or hexaDeciNum[j].compare("B") ==0 or hexaDeciNum[j].compare("C") ==0 or hexaDeciNum[j].compare("D") ==0 or hexaDeciNum[j].compare("E") ==0 or hexaDeciNum[j].compare("F") ==0 or hexaDeciNum[j].compare("1") ==0 or hexaDeciNum[j].compare("0") ==0 ) {
        answer = 1;
    }


}
    if (answer == 1){
        return hexaDeciNum;
    }
    else {
        return "ERROR";
    }
}


int main() {

    string word = "257";

    string answer = solution(word);

    return 0;

}

2 个答案:

答案 0 :(得分:4)

hexaDeciNum定义为string hexaDeciNum[100]。它不是string - 它是一个包含100个string实例的数组。

您试图从应该返回string的函数返回它。

答案 1 :(得分:0)

您应该将 hexaDeciNum 定义为string hexaDeciNum;而不是string hexaDeciNum[100];。通过这种方式,您仍然可以索引运算符。但是你不能再使用compare方法了,因为string的每个元素都是一个char。而是使用类似下面的运算符==作为您的代码。

// printing hexadecimal number array in reverse order
    for(int j=i-1; j>=0; j--){
        //cout << hexaDeciNum[j] << "\n";

        if (hexaDeciNum[j] == 'A' or hexaDeciNum[j]=='B' or 
            hexaDeciNum[j] == 'C' or hexaDeciNum[j] == 'D' or 
            hexaDeciNum[j] == 'E' or hexaDeciNum[j] == 'F' or 
            hexaDeciNum[j] == '1' or hexaDeciNum[j] == '0' ) {
            answer = 1;
        }
    }

请不要忘记使用-std=c++11编译器选项编译c ++ 11。