+ 1
why my code is giving size more than my input string?
https://code.sololearn.com/cpsJU308T6Xa/#cpp suppose my input is hello ,now it consists of 5 characters.when i call the reversed.size() it outputs 6 why?Am i using wrong function ?
3 Antworten
+ 4
@Shobhit it's probably because the size method returns the length of the string including the null terminator, hence it gives length+1.
Hth, cmiiw
+ 3
This is simply because you used += on the new string.
You see, the string constructor, when called during creation, does not allocate an empty string. Instead, it assigns 1 to your string. (Atleast here on Sololearn it works like this.).
Thus, to save the data, you should initialize reversal with "" or clear it.
Eg : string reversal = ""; reversal.clear();
If this doesn't work, Try reducing the initial variable to str.length() -1. It seems the loop is copying some variable that doesn't yet exist. Maybe a '\0'...
This will solve your problem...
+ 2
@Ipang
No, size and length are direct synonyms, and both return the same thing :
www.cplusplus.com/reference/string/string/size