What's wrong in this code? I am getting an error:
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;
}
};
Line 16: Char 16: error: no viable conversion from returned value of type 'int' to function return type 'std::string' (aka 'basic_string<char>')
return count;
CodePudding user response:
Your function declaration is string truncateSentence(string s, int k) which indicates you are returning a string, but then you have return count where count is an int.
Thus, the error.
So, you need to either:
change the return type to
int:int truncateSentence(string s, int k)convert the
intvalue to astringin thereturnstatement:return to_string(count);
