大家好,我试着寻找答案,但我找不到。 (我发现了如何使用它)但问题是我只是不知道为什么我的代码不起作用。 这是我的代码:
#include <iostream> #include <string> using namespace std; string acorta(string palabra, int carac) { string acortado; acortado=palabra; if(palabra.length() > carac) { return acortado; } else { acortado.resize(carac); return acortado; } } int main(int argc, char** argv) { cout<< acorta("Univesidad",5)<<endl; // here it should show "Unive" cout<< acorta("Secretariado",10)<<endl; //here it should show "Secretaria" cout<< acorta("Estudio",11)<<endl; //here it should show "Estudio" since th number is long than the word return 0; }好吧,程序应该接收一个字符串和一个整数,因为它应该返回字符串,只要int说。 例如(“笔记本电脑”,4)它应该返回“Lapt”。 如果int大于单词那么它应该返回整个单词。
问题是当程序不应该执行时,程序会返回整个单词。 所以我认为问题在于它不适用于我的功能。 如果我错了,请纠正我。
Hi everyone well I tried looking for an answer but I couldn't find. (I found how to use it) but the thing is that i just don't know why my code isn't working. Here is my code:
#include <iostream> #include <string> using namespace std; string acorta(string palabra, int carac) { string acortado; acortado=palabra; if(palabra.length() > carac) { return acortado; } else { acortado.resize(carac); return acortado; } } int main(int argc, char** argv) { cout<< acorta("Univesidad",5)<<endl; // here it should show "Unive" cout<< acorta("Secretariado",10)<<endl; //here it should show "Secretaria" cout<< acorta("Estudio",11)<<endl; //here it should show "Estudio" since th number is long than the word return 0; }well supposedly the program should receive a string and a integer because it should return the string as long as the int says. For example ("Laptop",4) it should return "Lapt". If the int is larger than the word then it should return the whole word.
The problem is that the program return the whole word when it shouldn't do the. So i think the the problem is that it is not going in to my function. Please correct me if i am wrong.
最满意答案
if(palabra.length() > carac)你告诉它返回原始字符串,如果它长于你传入的整数。你想要反转:
if(palabra.length() <= carac)更好的是,不要重复自己,也不需要不必要的参数副本,这已经是原始副本:
if(palabra.length() > carac) { palabra.resize(carac); } return palabra;或者,你可以使用substr函数,但如果你不想做不必要的子串,你可以调整它:
return palabra.substr(0, carac);如果你这样做,你甚至不再需要该字符串的副本:
string acorta(const string &palabra, int carac) if(palabra.length() > carac)You're telling it to return the original string if it's longer than the integer you pass in. You want to invert that:
if(palabra.length() <= carac)Better yet, don't repeat yourself and no need for unnecessary copies of the parameter, which is already a copy of the original:
if(palabra.length() > carac) { palabra.resize(carac); } return palabra;Or, you could make use of the substr function, though if you don't want to do needless substrings, you can tweak it:
return palabra.substr(0, carac);If you do that, you don't even need a copy of the string anymore:
string acorta(const string &palabra, int carac)更多推荐
发布评论