Reputation: 17
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.
Upvotes: 1
Views: 115
Reputation: 61930
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)
Upvotes: 5