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

C++ error returning a string from a function

本文关键字:C++ 错误 字符串 返回 函数      更新时间:2023-10-16

我正在尝试从函数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;
}

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

您正在尝试从应返回string的函数返回它。

您应该将hexaDeciNum定义为string hexaDeciNum;而不是string hexaDeciNum[100];。这样,您仍然可以索引运算符。但是,您不能再使用比较方法,因为字符串的每个元素都是一个字符。请对代码段使用如下所示的运算符==

// 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;
}
}

并且请不要忘记使用编译器选项为 C++ 11 编译它-std=c++11