【问题标题】:C++ Code Error: no viable conversion from returned value of type 'int' to function return type 'std::string' (aka 'basic_string<char>')C++ 代码错误:没有从类型 \'int\' 的返回值到函数返回类型 \'std::string\'(又名 \'basic_string<char>\')的可行转换
【发布时间】:2023-01-25 00:43:59
【问题描述】:

这段代码有什么问题。我收到一个错误 -

第 16 行:字符 16:错误:从“int”类型的返回值到函数返回类型“std::string”(又名“basic_string”)的转换不可行 返回计数;

class Solution {
public:
    string truncateSentence(string s, int k) {
        int count=0;
        for(char it : s){
            if(it == ' '){
                if(count<k){
                    count++;
                }
                else {
                    break;
                }
            }        
            
        }
        return count;    
    }
};

【问题讨论】:

  • Count 是一个整数,函数被声明为返回一个字符串。有什么不清楚的错误?

标签: c++ string truncate


【解决方案1】:

您的函数声明是 string truncateSentence(string s, int k),这表明您返回的是一个字符串,但是您有 return count 并且 count 是一个整数。

因此,错误。

【讨论】:

    猜你喜欢
    • 2019-05-18
    • 2021-02-28
    • 2021-12-18
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多